PART FOUR
INTERACTION
ABSTRACT CLASSES
Reminder
Make sure you have read the Coder's Handbook Entry on Abstract Classes before starting this section.
Terrain
Make this class abstract
Add two abstract methods in this class - nextDay() and clicked().
This will cause an error in class Cell, as we can no longer initialize each Cell's terrain to a generic terrain. Instead, initialize each terrain to Dirt.
It will also cause an error in Grass, Dirt, and Water. The error suggests you'll implement this in all of the subclasses. For now, create blank methods for clicked() and nextDay() in each subclass of Terrain.
By making an abstract method, we can assume that all Terrain objects can possibly do something on a click or nextDay event, but we don't need to define it in the superclass.
CLICK EVENTS
In this section, our goal is to allow the user to click on cells to change terrain. We'll first implement changes for the Dirt tile...
Dirt
When a Dirt tile is clicked, it should modify itself following these rules:
If it is not soil, it becomes soil
If it is soil but it is not wet, it becomes wet
Call setImage()
Cell
Create a method public void clicked()
This will simply call the terrain's clicked() method
World
Write a method called public boolean inBounds(int x, int y)
Returns true if the coordinates are within the array of cells and false otherwise.
Write a method called public void mousePressed(int button, int x, int y)
The x and y coordinates are in pixels. Meanwhile, cells are measured in an index position. You'll need to convert the pixel values to find which cell you have selected. (Hint: Divide by the cell's width or height respectively)
If the converted coordinates are inBounds, then call clicked() on the cell at those coordinates.
Game
In the mousePressed() method...
Call the World's mousePressed() method
CHECKPOINT
Run your code and see...
Clicking on Dirt tiles should change them to Soil
Clicking on Soil tiles should change them to Wet Soil
NEXT DAY
In this section, our goal is to allow the user to press a key trigger a new day. We'll start by having Dirt tiles dry out...
Dirt
When a Dirt tile is told it is the next day, it should:
No longer be wet
Call setImage()
Cell
Create a method called public void nextDay()
This will simply call the terrain's nextDay() method
World
Write a method called public void nextDay()
Loop through all the cells and call nextDay()
Game
In the keyPressed method()....
If the user presses the spacebar...
Call the world's nextDay() method
CHECKPOINT
Run your code and see...
When you press the key to start a new day, all wet soil is dried