Hello,
I would like to get the shark character in my game to be smarter and actually chase the Crab. Also, I would like to have a "You Win" appear after the Crab has eaten all the Worm Charcters in the game.
import greenfoot.*; // (Actor, World, Greenfoot, GreenfootImage)
public class CrabWorld extends World
{
private int wormsEaten;
/**
* Create the crab world (the beach). Our world has a size
* of 700x700 cells, where every cell is just 1 pixel.
*/
public CrabWorld()
{
super(750, 750, 1);
setPaintOrder(Crab.class, Worm.class, Shark.class);
populate();
randomWorms(5);
}
public void populate()
{
addObject (new Crab (), 200, 320);
addObject (new Shark (), 650, 650);
}
public void randomWorms(int howMany)
{
for(int i=0; i<howMany; i++) {
Worm worm = new Worm();
int x = Greenfoot.getRandomNumber(getWidth());
int y = Greenfoot.getRandomNumber(getHeight());
addObject(worm, x, y);
}
}
}
Shark Code:
import greenfoot.*;
/**
* Write a description of class Shark here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Shark extends Actor
{
private int crabsEaten;
/**
* Act - do whatever the Shark wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
move(-2);
Actor crab = (Actor)getWorld().getObjects(Crab.class).get(0);
turnTowards(Crab.getX(),Crab.getY());
if(foundWorm()) {
eatWorm();
}
}
public boolean atWorldEdge()
{
Actor shark = getOneObjectAtOffset(0, 0, CrabWorld.class);
if(CrabWorld.class != null) {
return true;
}
else {
return false;
}
}
public boolean foundWorm()
{
Actor worm = getOneObjectAtOffset(0, 0, Crab.class);
if(worm != null) {
return true;
}
else {
return false;
}
}
public void eatWorm()
{
Actor worm = getOneObjectAtOffset(0, 0, Crab.class);
if(worm != null) {
// eat the leaf...
getWorld().removeObject(worm);
crabsEaten = crabsEaten + 1;
}
}
public int getcrabsEaten()
{
return crabsEaten;
}
}
