Topic 7: Another Graphical Break!
As in Topic 5, this Topic will not introduce any new topics but will allow you to use the
GTGE graphical environment to get more practice with arrays. Today you are going to enhance your "move the
hero" application by introducing first one, then two monsters.
Object-Oriented Chase Game
Simple case: one monster
- Copy your Topic 5 project to a new project.
- Create a new class called Monster. This should be similar to Hero but should not contain score or lives attributes, or methods such as getScore(), getLives() etc. For an image you can use
this.
- Add getX() and getY() methods to Hero to return the x
and y coordinates.
- Add a new method to Monster called chase(). This method should take a parameter of data type
Hero and chase the hero. It should do this by comparing its own x and y coordinates with that of the
hero, so that:
- if the monster is to the right of the hero, it should move left;
- if the monster is to the left of the hero, it should move left;
- if the monster is above the hero, it should move down;
- if the monster is below the hero, it should move up.
- Add a method called eaten() to Monster. This should take a parameter of type Hero and should return true if the x and y coordinates of the monster and hero are the same, or false otherwise.
- Add a monster object to your main() from Topic 5 (the program where the user could move the
hero around).
- Add code to your Game's update() method
so that if the monster has eaten the hero the game quits
(System.exit(0);)
- Add code to the update()
to make the monster chase the hero, and display the monster.
- Test it out.
Intermediate exercise: Array of monsters
Now enhance your game so that there are three monsters, and not just one. Put the monsters in an
array and loop through the array to make all three monsters chase the hero. Initialise the monsters to
the following positions:
- First monster: x=getWidth(), y=getHeight()
- Second monster: x=getWidth(), y=0
- Third monster: x=0, y=getHeight()