SOMETHING LIKE THIS // public class Hippo extends Critter { private public Hippo
ID: 3644481 • Letter: S
Question
SOMETHING LIKE THIS
//
public class Hippo extends Critter {
private
public Hippo() {
moves = 0;
}
public boolean eat() {
moves++
if ( moves = 1 )
return true;
}else (
return false;
}
public Attack fight(String opponent) {
if (eat.equals("true"){
return Attack.SCRATCH;
}else
return Attack.POUNCE;
}
public Color getColor() {
if eat.equals("true"){
return Color.RED;
}else
return Color.WHITE;
}
public Direction getMove() {
moves++
???????????????
}
public String toString() {
return "%";
???????????????
}
}
Explanation / Answer
// Full Java code for Hippo class
import java.awt.*;
// hippos are directed by their hunger.
// They eat only when hungry, and their hunger is reduced whenever they eat.
// They are gray when hungry, and white when full.
// If they are hungry, they scratch. Otherwise, they pounce.
// They choose their direction randomly, but then keep it for 5 steps
public class Hippo extends Critter {
private Direction lastMove; // last direction hippo moved
private int numSteps; // number of steps taken in last direction (normally 1-5, 0 initially)
private int hunger; // hunger amount. Positive=hungry. 0=full.
// returns a random direction with uniform probability
private Direction randDirection() {
double r = Math.random();
if (r < 0.25) return Direction.NORTH;
if (r < 0.5) return Direction.EAST;
if (r < 0.75) return Direction.SOUTH;
return Direction.WEST;
}
// hippo starts walking in a random direction
public Hippo(int h) { hunger = h; numSteps = 0; lastMove = randDirection(); }
// hippo eats when hungry, and hunger amount is reduced by 1
public boolean eat() { if (hunger > 0) { --hunger; return true; } return false; }
// hungry hippos scratch. Full hippos pounce.
public Attack fight(String opponent) { if (hunger > 0) return Attack.SCRATCH; return Attack.POUNCE; }
// hungry hippos are gray. Full hippos are white
public Color getColor() { if (hunger > 0) return Color.GRAY; else return Color.WHITE; }
// move in same direction as before for 5 steps. Then choose a random direction.
public Direction getMove() {
if (numSteps < 5) { ++numSteps; return lastMove; }
lastMove = randDirection();
numSteps = 1;
return lastMove;
}
// hippos show the world how hungry they are
public String toString() { return String.valueOf(hunger); }
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.