Building Java Programs

Lab: Critters

 

 

Lab goals

Goals for this problem set:

Critters (syntax)

import java.awt.*;

public class ClassName extends Critter {
    fields, constructors...

    public boolean eat() { ... }
    public Attack fight(String opponent) { ... }
    public Color getColor() { ... }
    public Direction getMove() { ... }
    public String toString() { ... }
}

Exercise 1: Skunk errors

The following critter ( icon Skunk.java ) is an attempt to make a critter that goes W, W, N and repeats, unless he eats food, in which case he will start going W, W, S. But the file contains errors. Download it and fix the errors so it compiles/runs properly.

public class Skunk extend Critter {
    private int moves;
    private boolean hungry;
    
    public void Skunk() {  // constructor
        hungry = false;
    }
    public static boolean eat() {
        hungry = true;
        return true;
    }
    public Direction getmoves() {
        moves++;
        if (moves >= 3) {
            moves = 0;
        }
        if (moves == 1 && moves == 2) {
            return Direction.WEST;
        } else if (hungry) {
            return Direction.NORTH;
        } else if (!hungry) {
            return Direction.SOUTH;
        }
    }
}

Exercise 2: Butterfly 

Write a class Butterfly that extends the Critter class, along with its movement behavior. All unspecified aspects of Butterfly use the default behavior.

A Butterfly should be yellow in color. Its toString should alternate between being an x character and a - character each move.

A Butterfly flies upward in the following pattern: N, W, N, E, repeat.

Solve this program in jGRASP using the CritterMain simulator.

Exercise : Hyena

Write a class Hyena that extends the Critter class, along with its movement behavior. All unspecified aspects of Hyena use the default behavior.

A Hyena object moves in a rectangular pattern looking for food, walking NORTH, then EAST, then SOUTH, then WEST. Each time the hyena walks an entire rectangle, it starts the rectangle pattern over again but with a rectangle 1 step wider than before. The general pattern is as follows:

Solve this program in jGRASP using the CritterMain simulator.

Exercise 4: Hyena revisited

Modify your Hyena class from the previous problem to add eating behavior. If the hyena encounters food at any point during its movement pattern, it eats the food and starts the pattern over, lengthening the rectangular pattern by 1 in the process. For example:

 

Exercise 5: Shark 

Shark objects should alternate between moving to the north and south as follows: first move 1 step north, then 2 steps south, then 3 steps north, then 4 steps south, then 5 steps north, then 6 steps south, and so on, each time moving one farther than previously.

Solve this program in jGRASP with CritterMain,