Difference between revisions of "Greenfoot"

From CompSciWiki
Jump to: navigation, search
(added link to greenfoot page)
Line 255: Line 255:
  
 
===Full Example===
 
===Full Example===
The full example is available for download here.
+
The full example is available for download [http://www.greenfoot.org/scenarios/4723 here].
 
}}
 
}}

Revision as of 14:11, 4 April 2012

COMP 1010 Home > Back to Extra Labs

Introduction

This lab is an introduction to Greenfoot. Greenfoot is an interactive tool for building Java programs using a mixture of programming and interactivity. With Greenfoot, you are able to get a 2D graphic program up and running much faster than you would using regular Java.

To familiarize you with Greenfoot, we will show you how to build a simple Breakout game.

Step 0: Starting a New Scenario

Once you have Greenfoot open, the first thing you have to do is open a new scenario. To do this, follow these steps:

  1. Click on the "Scenario" menu tab at the top left of the window.
  2. Select "New..." from the list of options.
  3. Choose "Breakout" for your project name.
  4. Save project to either your own folder or the desktop so it is easy to find.
  5. Click "Create" to finish making your project.

Step 1: Making a New World

Now that you have a blank scenario open the next thing you have to do is add a new world for your game to exist in.

  1. Right click on the "World" button on the right side of the window.
  2. Select "New subclass..." from the list.
  3. Name this class "MyWorld"
  4. Select an image from the "background" catagory. This will be the main background of your game.
  5. Click "Ok" to finish creating this class.
  6. Press the "Compile" button on the bottom right hand side.

Notice how nothing changed before you pressed the compile button? The compile button is like a save button, none of the changes you make will take effect until you compile your program.

Step 2: Adding a Paddle

Setting Up the Paddle Class

First, right-click the following image and select Save As... and save it in the folder where you created your Greenfoot program.

Paddle.gif

On the right-hand side of your Greenfoot window, there are two boxes: One under "World classes" called "World" and another under "Actor classes" called "Actor".

Right-Click "Actor" and select "New subclass..."

Name your subclass Paddle by entering it into the New class name textbox. Now, for the image, click the "Import from file..." box in the bottom-left of this window. Find and select the Paddle.gif you just saved.

Press OK on that window to close it and create the new subclass.

In your main window, you want to add this newly created Paddle to your world. Press the compile button again to allow the Paddle you created to be usable. Then, right-click the Paddle box that now shows underneath the Actor box and select "new Paddle()".

Getting Your Paddle Onto the Game Screen

There are two ways to add the Paddle object to the game screen:

The first way is to select the "Paddle" box, which is now located under the "Actor" box on the right-hand side, and select "new Paddle()". When you do this, you'll now see the image of the paddle following your mouse cursor. You can now place the paddle in the game screen by clicking anywhere within it.

There is a problem with this way, however. If you click the "Compile" button, your paddle disappears! This is because it recompiled all the code within the world and classes to rebuild your game screen! To make your paddle stay in the world, you have to add it directly to the code. This is the second way of adding the paddle to the game screen.

To add your paddle to the code of the MyWorld class you made earlier, right-click the MyWorld box and select "Open editor".

You are now in the thick of actual Java programming!

In the editor, you will see the following code:

 import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class MyWorld extends World
{
    //Constructor
    public MyWorld()
    {
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
    }
} 

The code in block:

 public MyWorld()
{
    // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
    super(600, 400, 1);
} 

Is code that is used to build the game screen. Currently, it just has one line of code that creates a 600x400 pixel world. Now we want to add your paddle object to the world.

Under the super(...) line, type in:

 Paddle myPaddle = new Paddle();
addObject(myPaddle, 300, 380); 

This will add a paddle to the world, 300 pixels from the left side and 380 pixels from the top.

Because all this code is within

 public class MyWorld extends World
{
   ... all your code is in here!
} 

When you say addObject(...) in your code, it is performing this action on MyWorld using myPaddle, the number 300, and the number 380.

These actions are called methods or functions. The values that are being used -- myPaddle, 300, 380 -- are called parameters, which are values sent to a method.

In Java, methods are always called on an value called an object. In the above example, addObject(...) is performed on the MyWorld object.

Do not worry if you do not understand what this means right now; it will come with more practice.

If you press Compile on the game screen window, you will now see the paddle on the screen and it will stay there!

One problem with our code is that, if the size of the world ever changes, the paddle might not show up properly. Let's fix this. Change the earlier addObject code to:

 Paddle myPaddle = new Paddle();
addObject(myPaddle, getWidth() / 2, getHeight() - 20); 

Now, your paddle will always be in the middle of the screen, 20 pixels from the bottom, even if you change the values in the super(...) call and Compile.

Moving the Paddle

Right now, if you click "Act" or "Run" on the game screen window and press the left and right arrow keys, nothing happens. This isn't very game-like. We want our paddle to move around!

To do this, we need to add code to the Paddle class so it can control its own actions.

Right-click the "Paddle" box in the Actor classes box of the main window and select "Open editor", just like you did to change the code in MyWorld.

This opens up an editor with the following:

 ...

public class Paddle extends Actor
{
    /**
    * Act - do whatever the Paddle wants to do. This method is called whenever
    * the 'Act' or 'Run' button gets pressed in the environment.
    */
    public void act()
    {
        // Add your action code here
    }
} 

The comments in this code tell it all -- if you want you paddle to do anything, you have to add your code within the act() method. Change it so it looks like:

 public void act()
{
    if (Greenfoot.isKeyDown("left"))
    {
        setLocation(getX() - 3, getY());
    }
    else if (Greenfoot.isKeyDown("right"))
    {
        setLocation(getX() + 3, getY());
    }
} 

Let's break this code down:

 if (Greenfoot.isKeyDown("left"))
{
    ...
} 

This says that, when the user is pressing the "left" key, which is the left arrow on your keyboard, then do the code that is in it's block. The block:

 else if (Greenfoot.isKeyDown("right"))
{
    ...
} 

Does the exact same thing, except when the "right" key is pressed.

These two blocks contain:

 setLocation(getX() - 3, getY());
...
setLocation(getX() + 3, getY()); 

These both change the location of the Paddle object, except one has "getX() - 3" while the other has "getX() + 3". This means that one moves the Paddle to the left of it's current X position by 3 and the other to the right by 3. Try changing these values and even flipping them around to see how it changes your Paddle!

To test the changes, compile the code, press "Run" on the main window, and press your right and left keys. The paddle now moves!

Step 3: Creating a Bouncing Ball

To add a ball to your game you will need to create a new actor. Follow these steps:

  1. Right click on the "Actor" button
  2. Select "New subclass..." from the list of options.
  3. Name this class "Ball"
  4. Find and select the image "beeper.png" from the "other" catagory
  5. Press "Ok" to create the class.

Add a ball to your game

Before you can add the ball to your game you must first write the constructor. Add the following code above the act() method in the "Ball" file.

 private boolean left;
private boolean right;
private boolean up;
private boolean down;
private boolean gameOver;
public Ball()
{
     left = true;
     up = true;
     down = false;
     right = false;
     gameOver = false;
} 

Make the ball move

Step 4: Breakout Needs Bricks

To add bricks to the game we first need to create a brick class. To do this, follow these steps:

  1. Right click on the "Actor" button on the right side.
  2. Select "New subclass.." from the list.
  3. Name this class Bricks.
  4. Select the image "brick.png" from the "objects" catagory.
  5. Click "Ok" to finish creating this class.
  6. Compile your program.

You will not have to add any code for this object because it does not have to move. All we need to be able to do is make the brick appear and disappear.

Now if you want to add a brick to your game, you need to open the "MyWorld" source code file. Double click the "MyWorld" button on the right hand side to open the file. From here you can add a brick to your game by adding the following code into the "public MyWorld()" method:

 Bricks aBrick = new Bricks();
addObject(aBrick,100,100); 

The above code creates a single brick and adds it to the position (100,100). Since a single brick makes for a pretty boring game we need to add a lot more. To do this, add the following code into "MyWorld":

 int x,y;
x = 20;
y = 20;
        
//Create the bricks
for(int i = 0; i < 195; i++)
{
     // create a brick
     Bricks temp = new Bricks();
     // add brick to the world
     addObject(temp,x,y);
     // update coordinates
     x+=40;
     if(x >= 600)
     {
          x=20;
          y+=20;
     }
} 

The above code is creating 195 bricks and adding them to the world. Notice the variables x and y in the addObject() method. These variables are keeping track of where we want to place the bricks. Each time a brick is added we need to update the position of where the next one is placed. So after each brick is added "x+=40" says the next brick will be placed 40 pixels to the right. Since the width of our world is 600 pixels, we need to start a new row once x >= 600. To do this we update y by 20 pixels, starting the next row of bricks 20 pixels down. It is important to note that the top left of the game world has the coordinates (0,0) and there are no negative coordinates.

Full Example

The full example is available for download here.