//new to java /
Starting Your First Computer Game
Use Greenfoot to create your first interactive program.
MICHAEL KÖLLING
In the Premiere issue of Java Magazine, I wrote an article
about writing your first Java program using the Greenfoot
environment. In that article, we
made a turtle walk across the
screen, either in straight lines or
in circles.
Note: If you haven’t done so
already, go to that article to find
the software you need to install to
follow this project.
Getting an animated graphic
onscreen on your first day is pretty
good, but it gets boring after a
while if you can’t do anything
more with it. So today, I’ll tell you
how to add keyboard interac-
tion (that is, how to control your
turtle’s movement using keys),
which might be a first step toward
a little computer game.
■ ■ We need to be able to
check whether a key
has been pressed.
■ ■ We need a statement
in Java that lets us
state that we want to
turn only if the right
or left arrow key has
been pressed.
You can now
control a turtle
on your screen
with your arrow
keys. Pretty good
fun already!
name of the left arrow
key and—you guessed
it—right is the name of
the right arrow key.
The isKeyDown
method, when called,
will answer with a value
of either true (yes, the
left arrow key is being
pressed) or false (no,
the key is not being
pressed).
JAVA IN ACTION
Jumping Right In
When we left our turtle’s act method last time, it looked like this:
public void act()
{
move( 4);
turn( 2);
}
We observed that this caused
the turtle to run in a circle, be-
cause the act method is repeat-
edly executed when the program
runs (see Figure 1).
Checking for Key
Presses
Greenfoot has a method, called
isKeyDown, that lets us check
whether a given key on the key-
board is being held down. This
method is in the Greenfoot class.
We can, for instance, write the fol-
lowing to check whether the left
arrow key is being pressed:
Greenfoot.isKeyDown("left")
An if Statement
The second part we need to make
our plan work is a statement that
lets us execute an action (in our
case, turning) only under certain conditions (when the left or
right arrow key is pressed). This is
called an if statement.
An if statement has the following general form:
ABOUT US
The parameter (inside the
parentheses) is the name of the
key we want to check. The alphabetical keys have their character
as their name (for instance, the A
key is called a, the B key is called
b, and so on). The special control
keys have names indicating what
they are; for example, left is the
if (condition) {
statements;
}
blog
PHOTOGRAPH BY JOHN BLYTHE
Figure 1
When an if statement is executed, it checks the condition, and
then it executes the statements
between the curly brackets only