//new to java /
included in the project download) and
stop the game.
Listing 2 shows the complete implementation. Let’s briefly examine the
interesting aspects.
We have added the following line:
}
else {
...
}
LISTING 2
COMMUNITY
slices++;
The ++ operator, written after an int
variable, increments (that is, counts up)
this variable by 1. So we can see that we
are counting up every time after removing a pizza slice from the world.
Next, we have the following lines (with
some instructions in the place of the
three dots):
if(slices == 12) {
...
This code checks whether the slices
variable is now equal to 12 and, if it is,
executes the instructions between the
first pair of curly brackets. Otherwise (if
the variable is not 12), the instructions
after the else keyword are executed.
Note that we need to use a double equal
symbol (==) to check for equality.
Read Listing 2 carefully. You will see
that this code is used to play our slurping
sound and place a new pizza slice as long
as we have not eaten 12 slices yet. Then
it plays the fanfare and ends the game
when we have eaten 12 slices. Try the
code out in your own version of the game.
/**
Look for pizza and eat it if we see some.
*/
public void eat()
{
Actor pizza = getOneIntersectingObject( Pizza.class);
if(pizza != null) {
getWorld().removeObject(pizza);
slices++;
if(slices == 12) {
Greenfoot.playSound("fanfare.wav");
Greenfoot.stop();
}
else {
Greenfoot.playSound("slurp.wav");
placeNewPizza();
}
}
}
JAVA IN ACTION
Download all listings in this issue as text
Figure 2
Sharing Your Game
Now that our game is “complete”
in some sense—of course, no
game is ever truly finished—it
would be great if we could get all
our friends to try it out. Luckily,
we can.
Greenfoot has a ”share” function that allows you to upload
your program to the Greenfoot
Website, where other users can
play it and give you some feedback. You can see all the scenarios other Greenfoot users have
created by going to the Greenfoot
site and looking around.
To upload your own game,
click the Share button in the top
right of Greenfoot’s main window. Clicking it brings up a dialog box
that allows you to specify some details
for your upload (see Figure 2).
Your project will have a unique URL on
the Greenfoot Website. Send this to your
friends to show them the cool things you
have done!
ABOUT US
Conclusion
With this article, we have finished
building a simple computer game using
Greenfoot and Java. If you followed
along throughout this series, you will
have seen that building a simple game
in Java is not very hard. And you can
learn important programming concepts
along the way. Now take a look around
the Greenfoot site for some more ideas,
and continue to build your own games.
And above all, have fun! </article>
blog
23
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////////// MAY/JUNE 2012