This site requires JavaScript, please enable it in your browser!
Greenfoot back
SaveElephants
SaveElephants wrote ...

2018/11/1

how to manually feed an object

SaveElephants SaveElephants

2018/11/1

#
OK so I am trying to manually feed (add energy) my "friendly cat" to have him wake up. After 10 steps with out eating the pizza he falls asleep and you have to manually feed him to wake him up. Here is the code I have so far. I keep getting an error in the findPizza method where it says "greenfoot.Actor cannot be converted to Pizza"
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * 
 * FriendlyCat describes cats that 
 *  - move and jump when corresponding control keys are pressed, when having enough energy
 *  - love pizzas and show their joy by dancing after eating three pizzas
 * 
 */
public class FriendlyCat  extends Cat
{
    private int pizzaEaten=0;
    private int energy=10;
    public FriendlyCat()
    {
        energy=10;
        pizzaEaten=0;
    }

    public void act(){
        
        findPizza();
         if(energy<=0){
            sleep(1);
            return;
        }
         if (Greenfoot.isKeyDown("up")){
            jumpUp(1);
            energy--;
        }
        if (Greenfoot.isKeyDown("down")){
            jumpDown(1);
            energy--;
        }
        if (Greenfoot.isKeyDown("left")){
            walkLeft(1);
            energy--;
        }
        if (Greenfoot.isKeyDown("right")){
            walkRight(1);
            energy--;
        }
        
        
       
    }
    
    public void findPizza()
    {
        Pizza pizza = getOneIntersectingObject(Pizza.class);
    if(pizza != null)
    {
        eatPizza(pizza);
    }
    
    }
    public void eatPizza(Pizza pizza){
       
            eat();
            if(pizza !=null)
            {getWorld().removeObject(pizza);
            }
            pizzaEaten++;
            howManyEaten();
            energy+=5;
        
    }

    public void howManyEaten(){
        if (pizzaEaten==3){
            dance();
            pizzaEaten=0;
        }

    }
    
  
}
danpost danpost

2018/11/1

#
SaveElephants wrote...
I am trying to manually feed (add energy) my "friendly cat" to have him wake up. After 10 steps with out eating the pizza he falls asleep and you have to manually feed him to wake him up.
One possibility, maybe, is to use mouse clicks to manually feed the cat.
I keep getting an error in the findPizza method where it says "greenfoot.Actor cannot be converted to Pizza" << Code Omitted >>
It is not necessary to retain a reference to the intersecting pizza or to pass it to the eatPizza method. You could simply have:
public void findPizza()
{
    if (isTouching(Pizza.class)) eatPizza();
}

public void eatPizza()
{
    eat();
    removeTouching(Pizza.class);
    pizzaEaten++;
    howManyEaten();
    energy+=5;
}
You need to login to post a reply.