Last modified: January 07, 2023
Let's write your first Greenfoot program. By the end of this activity, you will have a simple game with a rocket moving across the outer space.
A scenario in Greenfoot is analogous to a project in BlueJ
In the top left corner, click on Scenario | New Java Scenario.
The pop-up window asks for you to give a name for your new scenario and a folder location to save the java files. For now, just use "HelloWorld" as project name and use the default folder location.
Click OK on the pop-up windows. Now, you should have a new scenario named "HelloWorld" created.
In order to proceed to the next few steps, let's first understand how greenfoot game work.
Every greenfoot game has one or more "World" that serve as the background of your game. A world can be configured into different width, height, background image, and more.
A world contains one or more "Actor" that serve as the characters in your game. They are called Actors because every few milliseconds or so, the greenfoot game engine lets that actor to "act", whether it is to move around, change its appearance, or interact with other actors.
We want our world to have a space image background.
To change the background image of MyWorld:
A rocket is an actor. In greenfoot, to create an actor, use the "create subclass" option by right-clicking the "Actor" yellow box.
On the pop-up window, name the actor "Rocket" and choose the rocket image, which is located at the bottom of the "transport" category.
To make the rocket move, click on the "Rocket" yellow box you just created and paste the following code into the act
method:
public void act() {
setLocation(getX() + 3, getY());
}
To add a rocket to the world, click on the "MyWorld" yellow box and paste the following code into the public MyWorld()
constructor:
public MyWorld() {
super(600, 400, 1);
Rocket r = new Rocket();
addObject(r, 100, 200); // adds the rocket to the world at x = 100 and y = 200
}
On your screen, you should now see a rocket ready to go.
Click on the "run" button at the bottom panel, and you should see a rocket moving horizontally from left to right!