import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* An empty small world with a cat.
*
* @author Michael Kölling
* @version 1.0
*/
public class CatWorld extends World
{
/**
* Constructor for objects of class CatWorld.
*
*/
public CatWorld()
{
// Create a new world with 20x20 cells with a cell size of 10x10 pixels.
super(600, 340, 1);
addObject (new MyCat(), 300, 250);
}
public void orderOutForPizza()
{
World myWorldAssistant = getWorld(); // need a world object to call world methods
int worldWidth = myWorldAssistant.getWidth();
int worldHeight = myWorldAssistant.getHeight();
myWorldAssistant.addObject( new Pizza(),
Greenfoot.getRandomNumber(worldWidth),
Greenfoot.getRandomNumber(worldHeight));
}
}
I am trying to make a code that can we used by the actor class
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* MyCat is your own cat. Get it to do things by writing code in its act method.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MyCat extends Cat
{
/**
* Act - do whatever the MyCat wants to do.
*/
public void act()
{
checkForPizza();
checkForKeyPress();
orderOutForPizza();
}
/**
* Cat walking back and forth hence pacing
*/
public void pace(int numberSteps)
{
walkLeft(numberSteps);
walkRight(2 * numberSteps);
walkLeft(numberSteps);
checkForKeyPress();
if ( Greenfoot.getRandomNumber(100) < 2 )
{
sleep(1);
}
}
public void jumpUpAndDown()
{
int amount = getImage().getHeight() / 2; // height of the jump is 1/2 height of cat image height
setLocation(getX(),getY() - amount);
wait(10);
setLocation(getX(),getY() + amount);
}
public void checkForPizza()
{
if ( isTouching(Pizza.class) )
{
removeTouching(Pizza.class);
eat();
orderOutForPizza();
}
}
public void checkForKeyPress() // NOTE if key is held down the action continues for left and right arrow keys
{
if ( Greenfoot.isKeyDown("left") )
{
walkLeft(2);
}
if ( Greenfoot.isKeyDown("right") )
{
walkRight(2);
}
if ( Greenfoot.isKeyDown("up"))
{
jumpUpAndDown();
}
}
}