GreenFoot è uno strumento software progettato per permettere ai principianti di fare esperienza con laprogrammazione orientata agli oggetti, OOP.
Permette lo sviluppo di applicazioni grafiche in Java.
Questo manuale è un’introduzione alla programmazione con Greenfoot.
Inizia dalle basi: prima tratta la creazione di scenari, poi la creazione di mondi e attori e così via.
Questo potrebbe non corrispondere all’esperienza di programmazione con GreenFoot che ciascuno possiede.
Infatti, il modo più comune usato quando si inizia a programmare con GreenFoot è di modificare uno scenario esistente.
In questo caso avresti già uno scenario, un mondo, e una o più classi di attori.
Salta liberamente al centro del manuale e comincia a leggere da lì.
Per esempio, potrebbe incuriosirti la creazione di immagini per gli attori oppure come trattare le collisioni.
Le sezioni di questo manuale sono state scritte con l’obiettivo di renderle indipendenti e quindi non è strettamente necessario leggere tutto in ordine.
Creare un nuovo scenario
La prima cosa da fare se si vuole creare un programma è creare uno scenario.
Farlo è semplice: scegli la voce di menu Scenario>Nuovo..., e scegli una destinazione e un nome per il tuo scenario.
GreenFoot creerà una cartella con questo nome che conterrà tutti i file associati al tuo scenario.
Lo scenario verrà aperto e vedrai una schermata simile a quella a destra.
Tutto qua: nel pannello delle classi ci sono le classi World e Actor e niente di più.
Sia World che Actor sono classi astratte, che significa: non si puoi creare oggetti.
In particolare non c’è un oggetto mondo perché non c’è ancora una classe mondo.
Come conseguenza, anche se avessimo un oggetto attore non potremmo posizionarlo da nessuna parte perché non possiamo ancora creare un mondo.
Per fare un passo abbiamo bisogno di creare sottoclassi di World e Actor.
In altre parole: dobbiamo definire il nostro mondo e poi definire uno o più attori.
Ecco con cosa inizierà la prossima sezione.
Nel sito di Grenfoot è disponibile un video tutorial che mostra come creare e impostare un nuovo scenario.
Utilizzare le API
Quando programmi con , è essenziale conoscere i metodi disponibili nelle classi standard di Greenfoot.
I metodi disponibili sono conosciuti come Greenfoot API, Application Programming Interface, e sono disponibili nel sito di Greenfoot.
Puoi selezionare l’opzione Aiuto>Documentazione Classi Greenfoot per aprire nel tuo browser la documentazione oppure fai doppio clic sulle classi World oActor.
Le API sono distribuite con GreenFoot, quindi non hai bisogno di essere connesso a Internet per esaminarli.
Greenfoot fornisce 5 classi che dovresti conoscere.
Esse sono World, Actor, Greenfoot, GreenfootImage e MouseInfo.
- Le classi World e Actor fanno da superclassi per i tuoi mondi e i tuoi attori.
- GreenfootImage è una classe che fornisce immagini e metodi per disegnare le immagini da utilizzare per i nostri mondi e per i nostri attori.
- Greenfoot è una classe che ci da l’accesso alla piattaforma Greenfoot stessa, per esempio per mettere in paisa l’esecuzione oppure per impostare la velocità.
- MouseInfo è una classe che fornisce informazioni sull’input del mouse, per esempio le coordinate dove si trovava il mouse quando è stato cliccato e su quale attore è avvenuto il clic.
Di tutte queste classi si parla più avanti.
Mentre programmi in GreenFoot, è una buona idea avere le API disponibili, stampate oppure in una finestra del browser.
Creare un mondo
To create a new world, select ‘New subclass…’ from the World class’s popup menu (see right).
After choosing a name for your new world and clicking Ok, you should see the new world in the class display.
Your new world class will have a skeleton that is valid and compiles.
You can now compile your scenario, and you will notice that the new world is automatically visible in the world view.
This is one of the built-in features of Greenfoot: whenever a valid world class exists, Greenfoot will, after every compilation, create one world object and show it in the world display.
In theory, you could have multiple world subclasses in a single Greenfoot scenario.
It is non-deterministic, though, which of those world will then be automatically created.
You could manually create a new world using the world’s constructor, but in practice we usually have only a single world subclass in every scenario.
Dimensione del mondo e risoluzione
Let us have a closer look at the code inside the new world class.
The default skeleton looks something like this:
public class MyWorld extends World
/** Costruttore per gli oggetti della classe MyWorld. */
super(20, 20, 10); // Crea un nuovo mondo con 20x20 celle con ogni cella di 10x10 pixel.
The first things we have to decide are the size of our world and the size of its cells.
There are essentially two kinds of worlds: those with large cells, where every actor object occupies only one single cell (that is: the cell is large enough to hold the complete actor), and those with small cells, where actors span multiple cells.
You have probably seen examples of both. ‘wombats’, for example, is one of the first kind, whereas ‘ants’ is of the second kind.
The wombats and ants scenarios are distributed as examples together with Greenfoot.
If you have not looked at them, and are not sure what we are discussing here, it would be a good idea to look at them now.
We can specify the world size and cell size in the super call in the constructor.
Assume we change it to
In this case, we will get a world that is 10 cells wide, 8 cells high, and where every cell is 60×60 pixels in size.
The signature of the World class constructor (which we are calling here) is
public World(int worldWidth, int worldHeight, int cellSize)
All positioning of actors in the world is in terms of cells.
You cannot place actors between cells (although an actor’s image can be larger than a cell, and thus overlap many cells).
Scegliere celle grandi o piccole
The trade-off to be made when choosing a world’s cell size is between smooth motion and ease of collision detection.
One result of the fact that actors can only be placed in cells is that worlds with large cells give you fairly course-grained motion.
Lo scenario wombats, per esempio, utilizza una cella di 60 pixel, e quindi, quando i vombati si muovono di un passo, la loro immagine si sposta sullo schermo di 60 pixel.
On the other hand, in worlds with large cells, where the actors are completely contained inside a cell, detecting other actors at one actor’s position is a bit simpler – we do not need to check for overlapping images, but simply for the presence of other actors in the same cell.
Finding actors in neighbouring cells is also easy.
We will discuss this in more detail in the section ‘Detecting other objects (collisions)’, below.
If you want smoother motion, you should use a smaller cell size. the ‘ants’ scenario, for example, uses 1-pixel cells, giving the ants the ability to move in small steps.
This can also be combined with large actor objects.
The ‘lunarlander’ scenario, for instance, uses a large actor (the rocket) on a 1-pixel cell world.
This gives the actor very smooth motion, since it’s location can be changed in one-pixel intervalls.
Immagini di sfondo
Most of the time, we want our world to have a background image.
This relatively easy to do.
First, you have to make or find a suitable background image.
There are a number of background images distributed with Greenfoot.
You can set one of these as the world’s background either when you create the class, or by selecting ‘Set image…’ from the class’s popup menu.
Select the ‘backgrounds’ category from the categories box, select an image and click Ok.
There are more background images available in the Greenfoot Image Collection on the Greenfoot web site.
To use a custom image, such as one from the Greenfoot Image Collection or one you have created yourself, place the image file into the ‘images’ folder inside your scenario folder.
Once the image file is there, it is available to your Greenfoot scenario, and you can select it from the ‘Scenario images’ box in the ‘Set image’ or ‘New subclass’ dialog.
You can also set the background image in the Java code with the line:
where “myImage.jpg” should be replaced with the correct image file name.
For example, assume we have placed the image “sand.jpg” into our scenario’s ‘images’ folder, then our world’s constructor might look like this:
super(20, 20, 10);
The background will, by default, be filled with the image by tiling the image across the world.
To get smooth looking background, you should use an image whose right edge fits seamlessly to the left, and the bottom to the top.
Alternatively, you can use a single image that is large enough to cover the whole world.
If you want to paint the background programmatically you can easily do so instead of using an image file.
The world always has a background image.
By default (as long as we do not specify anything else) it is an image that has the same size as the world and is completely transparent.
We can retrieve the image object for the world’s background image and perform drawing operations on it.
GreenfootImage background = getBackground();
These instructions will fill the entire bakground image with blue.
A third option is to combine the two: You can load an image file, then draw onto it, and use the modified file as a background for the world:
GreenfootImage background = new GreenfootImage("water.png");
background.drawString("WaterWorld", 20, 20);
Background images are typically set only once in the constructor of the world, although there is nothing that stops you from changing the world’s background dynamically at other times while your scenario is running.
Sometimes, when you have worlds with large grid sizes, you want to make the grid visible.
The ‘wombats’ scenario does this – you can see the grid painted on the background of the world.
There is no special function in Greenfoot to do this.
This is done simply by having the grid painted on the image that is used for the world background.
In the case of ‘wombats’, the world has 60-pixel cells, and the background image is a 60×60 pixel image (to match the cell size) that has a one pixel line at the left and top edges darkened a bit.
The effect of this is a visible grid when the tiles are used to fill the world background.
The grid can also be drawn programatically onto the background image in the world constructor.
Here is an example:
private static final Color OCEAN_BLUE = new Color(75, 75, 255);
private static final int ENV_SIZE = 12; // environment size in numer of cells
private static final int CELL_SIZE = 40; // cell size in pixels
private void drawBackground()
for(int i=0; i < ENV_SIZE; i++)
bg.drawLine(i*CELL_SIZE, 0, i*CELL_SIZE, ENV_SIZE*CELL_SIZE);
bg.drawLine(0, i*CELL_SIZE, ENV_SIZE*CELL_SIZE, i*CELL_SIZE);
Creare nuovi attori
This section discusses some of the characteristics of actor classes, and what to consider when writing them.
All classes that we want to act as part of our scenario are subclasses of the built-in ‘Actor’ class.
We can create new actor classes by selecting ‘New subclass…’ from the Actor class’s popup menu.
The following dialogue lets us specify a name and an image for our new class.
The name must be a valid Java class name (that is: it can contain only letters and numbers).
The class image will be the default image for all objects of that class.
Immagini delle classi
Every class has an associated image that serves as the default image for all objects of that class.
Every object can later alter its own image, so that individual objects of the class may look different.
This is further discussed in the section ‘Dealing with images’, below.
If objects do not set images explicitly, they will receive the class image.
The image selector in the dialogue shows two groups of images: project images and library images.
The library images are included in the Greenfoot distribution, the project images are stored in the ‘images’ folder inside your scenario (project) folder.
If you have your own images that you like to use for your class, you have two options:
- You can copy you image file into the scenario’s ‘images’ folder.
It will then be available for selection in this dialogue;
- or you can use the ‘Browse for more images’ button in this dialogue to select your image from anywhere in your file system.
The image will then automatically be copied into the images folder of the scenario.
As with most Java objects, the normal initialisation of the object happens in the object’s constructor.
However, there are some initialisation tasks that cannot be finished here.
The reason is that, at the time the object is constructed, it has not been entered into the world yet.
The order of events is:
- The object is constructed.
- The object is entered into the world.
During step 1, the object’s constructor is executed.
Since the object is not in the world at this time, methods such as getWorld(), getX() and getY() cannot be called in the constructor (when you’re not in the world, you do not have a location).
So, if we want to do anything as part of our initialisation that needs access to the world (such as create other objects in the world, or set our image depending on neighbouring objects), it cannot be done in the constructor. Instead, we have a second initialisation method, called ‘addedToWorld’.
Every actor class inherits this method from class ‘Actor’.
The signature of this method is
public void addedToWorld(World world)
This method is automatically called when the actor has been added to the world.
So, if we have work to do at the time the object has been added, all we have to do is to define an ‘addedToWorld’ method in our class with this signature and place our code there.
public class Rabbit extends Actor
private GreenfootImage normalImage;
private GreenfootImage scaredImage;
public void addedToWorld(World world)
private boolean isNextToFox()
... // calls getWorld() to check neighbours in world
In this example, the intention is that a rabbit, when placed into the world, looks ‘normal’ if it is not next to a fox, but looks scared when placed next to a fox.
To do this, we have two image files (“rabbit-normal.png” and “rabbit-scared.png”).
We can load the images in the Rabbit’s constructor, but we cannot select the image to show, since this involves checking the world, which is not accessible at the time the constructor executes.
When a user places an object into the world, things happen in this order:
- The object is created (and the constructor is executed).
- The object is placed into the world.
- The setLocation method of the object is called with its new location.
- The addedToWorld method of the object is called.
In our example above, by the time the addedToWorld method is called, the object is in the world and has a location.
So we can now call our own isNextToFox() method (which presumably makes use of the world and our location).
The setLocation() method will be called every time the location of the object changes.
The addedToWorld method is called only once.
The Lander class in the ‘lunarlander’ scenario (from the Greenfoot sample scenarios) shows another example of using this method.
Far muovere le cose
Every time a user clicks the ‘Act’ button on screen, the ‘act’ method of each object in the world will be called.
The ‘act’ method has the following signature:
public void act()
Every object that is active (i.e. is expected to do something) should implement this method.
The effect of a user clicking the ‘Run’ button is nothing more than a repeated (very fast) click on the ‘Act’ button.
In other words, our ‘act’ method will be called over and over again, as long as the scenario runs.
To make object move on screen, it is enough to modify the object’s location.
Three attributes of each actor become automatically and immediately visible on screen when you change them.
- the location (given as x and y coordinates)
- the rotation
- the image
If we change any of these attributes, the appearance of the actor on screen will change.
The Actor class has methods to get and set any of these.
The first thing to look at is location changes.
Consider, for example, the following code:
public void act()
int x = getX();
int y = getY();
The effect of this code fragment is to move the actor one cell to the right.
It does this by getting the actor’s current x and y coordinates, and then setting a new location for the actor with the x-coordinate increased by one.
We can write the same code a little shorter as
public void act()
Once our actor gets to the end of the world it keeps trying to move outside it, but Greenfoot will not let it.
To fix this, we need to add code that checks whether we can move in that direction before actually moving.
The ‘wombats’ scenario shows an eample of this.
The location coordinates are the indices of the cells in the world.
They should not exceed the world size.
The (0,0) location is in the top left of the world, and coordinates increase right (x) and down (y).
Cambiare la rotazione
In a similar manner to the location, we can change the rotation of the object’s image.
Here is an example:
public void act()
int rot = getRotation()+1;
if(rot == 360)
rot = 0;
This method gets the object’s current rotation, and then increases it by one.
The effect is that the object will slowly rotate clockwise.
The valid range for the rotation is [0..359], and the angle increases clockwise.
Thus, in the code example above, we check whether we have reached 360 (that is: left the valid range) and then reset the value to 0.
The last of the actor attributes that is automatically visualised is the actor’s image.
Changing the image will become immediately visible on screen.
public void act()
This code assumes that we have a hasEaten() method in our code, and then sets the image accordingly.
There are two versions of the setImage method: one expects a file name of an image file as a parameter, the other one expects an object of type GreenfootImage.
In general, it is a good idea to load image file only once into a GreenfootImage object, and then to reuse the same image object if you need to set the image multiple times.
For instance, instead of calling
repeatedly in the act method, you could initialise an instance field with the image:
private GreenfootImage happyImage=new GreenfootImage("happy.jpg");
and then set the image using this object:
More information about dealing with images is in the section ‘Dealing with images’ (below).
There is a tutorial video about making actors move available on the Greenfoot website.
Random behavior in Greenfoot scenarions is based on random numbers.
Generating random numbers in Greenfoot is fairly easy.
Greenfoot has a built-in class called ‘Greenfoot’ that is part of the framework (see The Greenfoot class, below).
This class has a method called getRandomNumber.
Its signature is
public int getRandomNumber(int limit)
In our own code, whenever we need a random number, we can call this method:
This example will give us a number in the range [0..9].
That is: the number is always between zero (inclusive) and the limit you specify (exclusive).
For details, see the description of the Greenfoot class in the Greenfoot API.
Once you have random numbers, using these for random behaviour is only a small step.
if(Greenfoot.getRandomNumber(2) == 0) // 50% chance
For more examples, see the ‘Wombat’ class in the ‘wombats2’ scenario, or the ‘Ant’ class in ‘ants’.
Trattare le immagini
Greenfoot supports various different ways that objects can acquire images.
Objects can get an image by using one of these three ways, or a combination of them:
- using default images from their class;
- loading image files from disk;
- containing code to paint an image.
All three method are used by the various objects in the ants scenario that is included in the Greenfoot distribution.
It is useful to study this example if you want to learn about images.
We will refer to this scenario repeatedly in this section.
We discuss all three methods in turn.
There are also tutorial videos available on the Greenfoot website showing how to make background images using these methods.
Using default class images
Every class has an associated image.
This image is usually assigned when creating the class, but may be changed later using the ‘Set Image…’ function from the class’s popup menu.
For an object to use the class’s image, there is nothing we need to do.
If we write no special image handling code, this is the image that will be used to display objects of this class.
In the ants project, the AntHill objects use this technique.
A fixed image is assigned to the class, and all AntHill objects look the same.
Utilizzare file immagine
We can easily alter the image of an individual object by using the Actor’s ‘setImage(..)’ method.
In the ants scenario for example, the Ant class uses this method.
When an ant finds some food, its takeFood() method is executed, which includes the line
When the ant drops the food (in the dropFood() method) it uses this line:
This way, the image of each individual ant object can dynamically change.
When this ‘setImage’ method is used, an image file is loaded from disk.
The parameter specifies the file name, and the file should be located in the project’s ‘images’ folder.
If images of objects change frequently, or have to change quickly, this can be optimised by loading the image from disk only once, and storing them in an image object (of type GreenfootImage).
Here is a code snippet to illustrate this:
public class Ant extends Actor
private GreenfootImage foodImage;
private GreenfootImage noFoodImage;
foodImage =new GreenfootImage("ant-with-food.gif");
private boolean takeFood()
private boolean dropFood()
This example illustrates a second version of the setImage method: setImage can also be called with a GreenfootImage as a parameter, instead of a file name.
The GreenfootImage can be constructed using the image file name, and the resulting object can then be reused.
This version saves resources and executes quicker.It is preferrable whenever the images change frequently.
The file names of image files are case-sensitive in Greenfoot.
For example, “image.png”, “Image.png” and “image.PNG” are all different.
You have to use the correct case or Greenfoot will not be able to find your image.
Utilizzare immagini generate
Images can be generated at run-time by code included in your class.
This approach can be useful when there will be many variations of the image, and they can be drawn simply.
In the ants scenario the Food class uses this approach so it can show how many pieces of food remain in the pile and the Pheromone class uses it to show its intensity decreasing.
Creating an image object
To start generating an image, you need a GreenfootImage object to work with.
This can be a blank image, an image from a file, or the default class image.
To create a blank image, you need to pass the width and height of the desired image to the GreenfootImage constructor.
The image will be completely transparent.
GreenfootImage image=new GreenfootImage(60, 50); //Creates an image 60 pixels wide and 50 pixels high
If you are using a GreenfootImage which already exists you may want to create a copy of the image to draw on, so that the original is preserved.
GreenfootImage image_copy=new GreenfootImage(image);
Disegnare su un’immagine
Once you have your image to draw on, whether it be blank or already contain a base image, you can use some of theGreenfootImage class’s methods to add to the image.
The GreenfootImage class provides methods that let you:
- Draw straight lines, rectangles, ovals (including circles) and polygons
- Draw filled rectangles, ovals and polygons
- Set the colour of individual pixels
- Fill the entire image with a single colour
- Draw a string of text on the image
- Copy another GreenfootImage onto the image
- Scale, rotate and mirror the image
- Set the transparency of the image
Impostare il colore
Before using any of the drawing methods, you need to tell the image what colour you want to draw in.
To do this, call the GreenfootImage object’s setColor() method.
This takes a Color object from Java’s library.
The easiest way to get a Color object is to use one of the pre-defined constants in the Color class, such as Color.BLACK.
Other colours available include white, gray, red, green, blue, yellow and orange.
See the Java API documentation of the Color class for a full list of pre-defined colours and other ways of getting Color objects.
As we are using a class from the Java library we have to say where to find it.
To do that, we add an ‘import’ statement to the top of the class file.
There is already one there which says where to find the Greenfoot classes.
We add another line importing the Color class, whose fully-qualified name is java.awt.Color.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
Then we can go ahead and set the colour we want to draw with, in whichever method we are generating the image:
Tracciare una linea
To draw a line on the image, use the drawLine() method.
It takes four parameters, the first two represent the x and y co-ordinates for the start of the line, and the last two are the x and y co-ordinates of the end of the line.
The co-ordinates start at (0,0) at the top-left of an image, and are measured in pixels.
This is similar to how actors are placed in the world, except that the world uses cells which can be larger than one pixel, andGreenfootImage always measures in pixels.
The following code will draw a line 15 pixels long across the top of an image:
image.drawLine(0, 0, 14, 0);
The line starts at (0, 0) which is the top-left of the image, and ends at (14,0).
The x co-ordinate of the 15th pixel is 14, as the first pixel is numbered 0.
If you were drawing a line across the entire top of an image, the code would be:
image.drawLine(0, 0, image.getWidth()-1, 0);
This code will draw a line from the top-left of an image (0, 0) to halfway down the right-hand side (59, 25) (of a 60×50 pixel image):
image.drawLine(0, 0, 59, 25);
Disegnare cerchi, rettangoli e altre figure
Rectangles can be drawn using the drawRect method.
The method takes four parameters: the x and y co-ordinates of the top-left corner of the rectangle, its width and its height.
The following code would draw a rectangle 60 pixels wide by 30 pixels high in the top-left corner of the image:
image.drawRect(0, 0, 60, 30);
The rectangle covers an area that is width+1 pixels wide and height+1 pixels tall.
This means if you want to draw a rectangle around the edge of an image, use the following code:
image.drawRect(0, 0, image.getWidth()-1, image.getHeight()-1);
Circles and ovals can be drawn by calling the drawOval method, specifying the co-ordinates of the top-left corner of the area that the oval is to be drawn in, and the width and height of the oval.
Unlike with rectangles, the co-ordinates given will not be on the line which is drawn: the left of the circle will be at the x co-ordinate, and the top of the circle will be at the y co-ordinate.
To draw an oval 20 pixels wide and 10 pixels tall at position (5,10) you would use the following parameters:
image.drawOval(5, 10, 20, 10);
Like rectangles, ovals cover an area that is width+1 pixels wide and height+1 pixels tall.
You can draw more complicated polygons using the drawPolygon method, which takes an array of x co-ordinates, an array of y co-ordinates and the number of points the shape has.
Lines are drawn between each set of co-ordinates in turn, and then from the final point to the first point (the polygon is closed).
For each of these three methods there is also ‘fill’ version, which draws a filled-in shape, rather than just the shape’s outline.
The fill uses the same colour as the outline, which is the colour most recently passed to the image’s setColor method.
To draw a shape with different fill & outline colours, call the fill version of the method with one colour, then the outline method using a different color:
image.fillRect(5, 10, 40, 20);
image.drawRect(5, 10, 40, 20);
Scrivere sulle immagini
You can use the drawString method to put text into an image.
The method takes the string to be drawn, and the x and y position of the baseline of the first character.
This means that the point specified will almost be the bottom-left corner of the area where the text is drawn, except that the bottom of letters such as p and q will fall below that point.
You can set the font using the setFont method, passing it a Font object.
The easiest way to get a font object with a specific text size is to use the deriveFont method on another font object.
You can get the current font that the image is using from the getFont method.
To store a Font object in a variable, we first need to add an import statement to the top of the class to say where the Font object is:
The code below (taken from the ScoreBoard class in the balloons example) can then be used to get a font whose size is 48 points:
Font font = image.getFont();
font = font.deriveFont(48);
That font will then be used for any following drawString method calls:
image.drawString(title, 60, 101);
To get a font with a certain style, such as serif/sans-serif or bold/italic/underlined, see the Font class’s constructors in the Java Library Documentation for the Font class.
There is a tutorial video about this available on the Greenfoot website.
Copiare un’immagine dentro altre immagini
GreenfootImage provides a method to draw one image onto another image.
This can be useful if you want to add an icon to an actor’s image to show something special about that actor, such as if it’s carrying something.
To draw one image onto another, simply call the drawImage method on the image to draw to, passing the image to copy from and the co-ordinates that the image should be placed at.
image.drawImage(new GreenfootImage("smaller-image.png"), 10, 10);
Scalare, riflettere e ruotare immagini
Images can be scaled (stretched or compressed), mirrored vertically or horizontally, and rotated.
The scale method takes two integers as parameters, which represent the width and height that you want the image to be.
The image will then be stretched (or made smaller) to fit that size.
To mirror an image, use one of the mirrorVertically or mirrorHorizontally methods.
They take no parameters and flip the image along the appropriate axis.
Images can be rotated using the rotate method, which takes the number of degrees to rotate the image by.
Note that if you rotate the image by anything which is not a multiple of 90 degrees then what was in the corners of the image will be cut off, as the image will still have horizontal and vertical edges.
If the image is to be used as an actor’s image, then usually rotation is better achieved by using the Actor object’s setRotation method, as it just displays the image at a different rotation, rather than changing the image itself.
Also, the Actor’s setRotation method remembers its rotation, which can be used to work out which direction the actor should move in, whereas the GreenfootImage objects’ rotate method just rotates the image the specified number of degrees from whatever rotation it is at the moment.
The image can be made partially transparent by using the setTransparancy method.
This will allow you to see other objects and the world’s background through the image.
The method takes one parameter, which should be a number between 0 and 255, where 0 means completely invisible and 255 means completely visible.
The image will not be able to be seen by the user at low numbers; with a patterned background it can get difficult to see anything with a transparency up to about 40.
However, the actors will still be found by the collision detection methods.
If there is an actor which can be collided with, which the user is suposed to avoid, and which is fading out using transparency, it is a good idea to remove it from the world when the transparency gets low, but before it reaches zero.
Trattare i singoli pixel
You can set the colour of any specific pixel by using the setColorAt method, passing the x and y co-ordinates of the pixel and the colour to set it to.
The ‘Food’ class in the ‘ants’ example scenario uses this method.
It loops through all the pieces of food left in the pile, and for each one draws four pixels onto the image next to each other in a random position.
The colours of the pixels were chosen to give a 3D effect on the pieces of food.
GreenfootImage image = new GreenfootImage(SIZE, SIZE);
for (int i=0; i<crumbs; i++)
image.setColorAt(x , y , color1);
image.setColorAt(x+1, y , color2);
image.setColorAt(x , y+1, color2);
image.setColorAt(x+1, y+1, color3);
Individuare altri oggetti (collisioni)
One of the really nice features in the Greenfoot API is the ability to find other objects in the world.
As soon as you want objects to interact with each other, you need to be able to “see” these other objects.
Greenfoot gives you many different ways to find other objects to suit many different kinds of scenarios.
We have divided the methods into two different categories: one that is strictly based on the location of objects, and one that is using the image representation of the objects.
The methods discussed here are all available when sub-classing the Actor class.
In some scenarios, like Wombats, objects are always entirely contained within a cell, and you are only interested in the location of the object in the grid.
For these scenarios we have methods that works strictly on the location of the objects.
We call these methods for cell based.
When wombats are looking for leaves to eat, they look at where they are right now, to see if there is a leaf.
In the foundLeaf() method in the Wombat the code to do this is:
Actor leaf=getOneObjectAtOffset(0, 0, Leaf.class);
This method returns one object at a relative location to where the wombat is currently.
The first two parameters specify the offset from the current location, which in this case is (0,0), since wombats can only eat leaves where they are right now.
The third parameter specifies which types of objects we are looking for.
The method will then only return objects of the given class or sub-class.
If several objects exist at the location, it is undefined which one will be returned.
If you have a really big wombat that can eat several leaves at once you can use another method which will return a list of leaves:
List leaves=getObjectsAtOffset(0, 0, Leaf.class);
The wombats, as they are implemented in the wombats scenario, are pretty dumb and do not make use of any of the senses that real wombat has.
If we want the wombat to look around for leaves before moving we have several methods to choose from.
If the wombat should only be able to look at the immediate neighbours to the north, south, east and west we can use the following methods
List leaves=getNeighbours(1, false, Leaf.class);
That call will find all objects within a walking distance of 1 cell, where you are not allow to go diagonally.
If you wanted the diagonals included you should replace false with true.
If the wombat should be able to look farther you can increase the distance from 1 to something larger.
Below we have made a few pictures to illustrate what cells will be considered when looking for neighbours with different parameters for the method call.
Without the diagonal:
getNeighbours(1, false, Leaf.class);
With the diagonal:
getNeighbours(1, true, Leaf.class);
A method related in functionality to the getNeighbours methods:
List leaves=getObjectsInRange(2, Leaf.class);
This method call will return all objects (of the class Leaf and subclasses) that have a location that is within 2 cells.
If the distance between two actors is exactly 2, it is considered to be in range.
See the picture below for an illustration of this
Sometimes it is not precise enough to use the cell location to determine collisions.
Greenfoot has a few methods that allow you to to check whether the graphical representations of actors overlap.
Be aware that these method calls require more computation than the cell based methods and might slow down your program if it contains many actors.
Input da tastiera
There are two ways that the keyboard can be used in Greenfoot scenarios: holding a key down for a continuous action, or pressing a key for a discrete action.
Keys on the keyboard, when being passed to or returned from a method, are referred to by their names. The possible names are:
- “a”, “b”, .., “z” (alphabetical keys)
- “0”..”9″ (digits)
- most punctuation marks
- “up”, “down”, “left”, “right” (the cursor keys)
- “enter”, “space”, “tab”, “escape”, “backspace”
- “F1”, “F2”, .., “F12” (the function keys)
Continuous actions: holding a key down
The lunarlander example scenario uses this method: while the ‘down’ cursor key is pressed the lander’s thruster is fired.
This is achieved using the isKeyDown() method of the Greenfoot class.
In an actor’s act method you can call this method with a key’s name as the parameter, and it will return true if that key is currently being held down.
You can use this in the condition of an if-statement to make the actor act differently or look different, depending on whether the key is down or not:
In this method, when referring the the alphabetical keys either the uppercase or lowercase letters can be used as the parameter to the method.
Single actions: hitting a key
The getKey() method of the Greenfoot class can be used to get the name of the most recently pressed key since the previous time the method was called.
This can be used for single actions where the key is to be hit once, rather than held down, such as a ‘fire bullet’ action:
When comparing strings, unlike comparing numbers, it is much better to use the string’s equals method than to use the ==equality operator, as strings are objects (like actors are objects) and the == equality operator, when used on objects, tests to see if they are the same object, not if they have the same contents.
Note that as the method returns the last key pressed down since the last time it was called, if the method has not been called for a while then the key returned might not have been pressed recently – if no other key has been pressed since.
Also, if two keys are pressed at once, or close together between two calls of getKey, then only the last one pressed will be returned.
Input con il mouse
You can test if the user has done anything with the mouse using these methods on the Greenfoot class: mouseClicked, mouseDragged, mouseDragEnded, mouseMoved and mousePressed.
Each of these methods take an object as a parameter.
Usually this will be an Actor to find out if the mouse action (click, drag over, move over, etc) was on or over that actor.
The parameter can also be the world object, which finds out if the mouse action was over an area where there were no actors, or null which finds out if that mouse action happened at all irrespective of what actor it was over.
If the appropriate mouse action has been performed over the specified actor or world then the method returns true, otherwise it will return false.
If the mouse action was over a number of actors, only the top one will return true.
These methods will only return true for the world if the mouse action was not over any actors at all.
If the methods are called from an actor’s act method then usually the parameter will be that actor object, using the this keyword.
For example, an actor could use the following code to change its image when it is clicked.
clickedImage would be a field containing a GreenfootImage object, but the this keyword is not a variable and so does not need to be defined anywhere.
- The mousePressed() method is used to find out if the mouse button was pressed down, whether or not it has been released again yet.
- mouseClicked is used to find out if the mouse has been released after it has been pressed.
- That is, it finds out if the mouse has been pressed and released.
- mouseMoved is used to find out if the mouse has been moved over the specified object (while the button is not pressed down).
- mouseDragged is used to find out if the mouse has been moved over the object with the mouse button pressed down.
- mouseDragEnded is used to find out if the mouse has been released after having been dragged.
Additional information can be acquired from a MouseInfo object returned from the getMouseInfo method.
Using this object you can find out the actor that the action was on or over (if any), the button that was clicked (i.e. left or right mouse button), the number of clicks (single or double), and the x and y co-ordinates of the mouse.
This information is used by the balloons example scenario.
The mouseMoved() method (using null as the parameter as the move does not have to be over a specific actor) and the getX()and getY() methods of the MouseInfo object are used to move the dart around:
The mouseClicked() method is used to pop the balloons.
The getActor() method of the MouseInfo class is not used in this case, as it will always return the dart, and the point at which we want to test for a balloon is not where the mouse is, it is at the tip of the dart.
A tutorial video about handling mouse input is available on the Greenfoot website.
Playing a sound in Greenfoot is extremely simple.
All you have to do is copy the sound file to be played into your scenario’s sounds folder, and then call the Greenfoot class’s playSound method with the name of the sound file to be played.
For example, the lunarlander scenario plays a sound file called Explosion.wav if the lander crashes into the moon’s surface.
This file is in the lunarlander/sounds folder, and is played by the following line of code:
The audio file must be a wav, aiff or au file.
Mp3 files are not supported, and not all wav files are supported.
If a wav file does not play, it should be converted to a Signed 16 bit PCMwav file.
This can be done with many audio programs, for example the excellent and free Audacity has an Export function that will do the conversion.
Sound file names are case-sensitive (i.e. sound.wav, Sound.wav and sound.WAV are all different); if you use the wrong case you will get an IllegalArgumentException as the sound will not be able to be played.
Controllare lo scenario
The Greenfoot class provides methods to control the execution of the scenario, and the World class provides methods to control how the scenario looks, as well as to react to the scenario stopping or starting.
The Greenfoot class allows you to stop, start, pause (delay) and set the speed of the action (as well as providing the mouse, keyboard & sound methods mentioned earlier).
The World class allows you to set the order in which the actors are painted on the screen, set the order in which the actors have their act method called, respond to the scenario being started and respond the the scenario being stopped.
Stopping the scenario
The Greenfoot.stop() method allows you to stop the scenario, which is usually done when everything has finished.
if(getY() == 0)
Calling the stop method is equivalent to the user pressing the Pause button.
The user can then press Act or Run again, but in the example code above as long as the if-statement’s condition returns true every time it is called after the scenario should stop then pressing the Run button again will have no effect.
Setting the speed
You can set the speed of execution using the Greenfoot.setSpeed() method.
It is good practice to set the suggested speed in the World’s constructor.
This following code sets the speed at 50%:
The Greenfoot.delay() method allows you to suspend the scenario for a certain number of steps, which is specified in the parameter.
Note that the length of time that the scenario will be delayed for will vary a great deal, based on the speed of execution.
Greenfoot.delay(10); //Pause for 10 steps
All actors will be delayed when the delay method is called; if you want some actors to continue moving, or may in the future want to add an actor that continues moving during that time, then it would be better to have a boolean field or method that is false when you want to delay and true the rest of the time.
Then all the actors that should stop can check at the beginning of their act methods:
public void act()
Starting the scenario
The Greenfoot.start() method is very rarely used, as most of the code that is written in scenarios is only executed after the scenario has been started.
However, while the scenario is stopped the user can call methods of the actors in the world form their popup menus.
In this situation, calling Greenfoot.start() from within a method will make sure that the scenario starts running if the method is called from the popup menu.
For example, in the balloons scenario you can start the scenario, allow some balloons to appear, pause the scenario and then call the pop method on each balloon.
If you added the following code to the pop method then the scenario would re-start as soon as a user tried to pop a balloon through the popup menu.
public void pop()
Setting the order actors are painted in
The setPaintOrder method of the World class sets the order in which the actors are painted onto the screen.
Paint order is specified by class: objects of one class will always be painted on top of objects of some other class.
The order of objects of the same class cannot be specified.
Objects of classes listed first in the parameter list will appear on top of all objects of classes listed later.
Objects of a class not explicitly specified effectively inherit the paint order from their superclass.
Objects of classes not listed will appear below the objects whose classes have been specified.
This method is usually only called from the constructor of your subclass of World, such as in the ants scenaro:
setPaintOrder(Ant.class, Counter.class, Food.class, AntHill.class, Pheromone.class);
where objects of the Ant class would always appear above (that is, completely visible when they overlap) actors of other classes.
To call the method from within an actor class, you would first have to get the current world object using the getWorld() method:
Setting the order actors act in
The setActOrder() method of the World class sets the order in which the actors act() methods are called.
Similar to setPaintOrder(), the act() order is set by class and the order of objects of the same class cannot be specified.
When some classes are not specified in a call to setActOrder() the same rules apply as for setPaintOrder().
In each turn (such as one click of the Azione button) the act method will be called on every object of the class which was listed first in the call to setActOrder(), then on every object of the class which was listed second, and so on.
Responding to the scenario being started or stopped
When the scenario is started Greenfoot will call the started method of the current world object, and when the scenario is stopped it will call the stopped method.
If you want to run some code when these events happen, override these methods in your subclass of World.
To ‘override’ a method in a subclass, you simply declare a method with the same name, such as how you override the act method from Actor in every subclass of it that you create.
public void started()
// ... Do something when the scenario has started
public void stopped()
// ... Do something when the scenario has stopped
Utilizzare classi di supporto
Ci sono un certo numero di classi riutilizzabili che sono disponibili per i tuoi progetti.
Ti possono aiutare ad ottenere effetti e funzionalità per i tuoi scenari che potresti ottenere da solo, ma dedicandoti per molto tempo, oppure che non potresti ottenere per insufficiente esperienza di programmazione.
- Alcune delle classi di supporto sono anche attori e puoi inserirle direttamente nei tuoi scenari (come Explosion).
- Altre sono sottoclassi astratte di Actor (come SmoothMover) che dovrai completare con i tuoi Actor fornendo così delle funzionalità aggiuntive ai tuoi Actor .
Infine alcune non sono attori ma utilità che gli attori possono utilizzare (come Vector che è utilizzato da SmoothMover.
La lista ufficiale delle classi di supporto di Greenfoot: http://greenfoot.org/programming/classes.html.
C’è anche una collezione di classi di supporto nella galleria di Greenfoot Gallery: http://greenfootgallery.org/collections/4.
Per utilizzare una qualsiasi delle classi di supporto devi prima scaricare il suo codice sorgente.
Selezionando il nome di una classe, nella lista ufficiale delle classi di utilità, visualizzerai il suo codice sorgente.
Con il pulsante destro sul collegamento si può salvare il file sorgente .java.
Nella galleria, clicca sul nome dello scenario per andare alla sua pagina.
Qui potrai provare lo scenario o ottenere il sorgente selezionando il collegamento Download.
Ci sono due modalità per copiare una classe di supporto in uno scenario:
- La più semplice è creare una classe con il nome appropriato nello scenario, poi copiare l’intero contenuto del sorgente della classe di supporto e copiarlo sopra l’intero contenuto della classe appena creata nello scenario.
- L’altra modalità è salvare i file della classe nella cartella dello scenario.
If you are using a support class from the official list, then save the .java file into your scenario folder.
If you are using a class from a gallery scenario, copy across the file with the same name as the class with a .java extention from the gallery scenario’s folder to your scenario’s folder.
You can also copy across the files with the same name as the class and the .class and .ctxt extentions, but you do not have to.
Nota che alcune classi di supporto utilizzano altre classi, immagini o suoni, quindi devi copiare tutto nel tuo scenario per usare la classe. (Per esempio l’attore astratto SmoothMover richiede la classe di supporto Vector e l’attore Explosion richiede un’immagine e un suono. Ogni risorsa deve essere copiata nella cartellla corrispondente images e sounds.)
Usare attori riutilizzabili
Dopo aver copiato un attore riutilizzabile nella tua classe, dovrebbe essere pronto per essere utilizzato come qualsiasi altro attore nello scenario: puoi istanziarlo, creare sottoclassi, impostare la sua immagine e modificarne il codice.
Usare attori astratti
Alcune classi di supporto sono astratte. Significa che non puoi istanziarle (non puoi inserirle direttamente nel mondo) allo stesso modo della classe Actor. Per utilizzarle crea attori che siano sottoclassi delle sottoclassi astratte
- selezionando Nuova sottoclasse... dal menu contestuale
- oppure modificando la classe dopo la parola chiave extends da sottoclasse di Actor a sottoclasse della classe astratta. Per esempio, per far diventare un attore esistente di nome MyActor una sottoclasse della classe SmoothMover, cambia la linea nel codice sorgente di MyActor da:
class MyActor extends Actor
class MyActor extends SmoothMover
MyActor sarà ancora un’estensione di Actor in quanto SmoothMover estende Actor e MyActor estende SmoothMover.
Usare classi di supporto
Per utilizzare classi di supporto che non sono attori o attori astratti copiale nel tuo scenario allo stesso modo delle altre classi di supporto.
Siccome non sono attori non puoi inserirle nel mondo, sono fatte per essere usate come codice sorgente per gli attori.
Per esempio la classe di supporto Vector è utilizzata per memorizzare un vettore di movimento (una direzione e una velocità) che è utilizzato dalla classe SmoothMover per memorizzare il suo movimento.
Queste classi possono essere create, memorizzate in variabili e i loro metodi vengono chiamati come qualsiasi altro oggetto.
Creare classi di supporto
Se crei una classe, e vuoi condividerla, crea uno scenario dimostrativo per la classe e caricalo nella galleria di Greenfoot con l’etichetta demo, controllando di includere anche il codice sorgente.
Gli altri utenti della galleria potranno visionarlo, provarlo, lasciare dei commenti e scaricarlo per utilizzarlo e potrebbe anche essere aggiunto alla collezione delle classi di supporto…
Esportare uno scenario
Greenfoot fornisce tre modalità per esportare uno scenario, tutte disponibili dalla voce di menu Scenario > Esporta....
Le tre opzioni sono:
- Pubblicare lo scenario nella galleria di GreenFoot
- Esportare lo scenario come pagina web
- Esportare lo scenario come applicazione
La galleria di GreenFoot si trova all’indirizzo http://www.greenfootgallery.org e fornisce agli utenti di GreenFoot una modalità per condividere con gli altri i loro scenari, per provare gli scenari degli altri e per dare e ricevere opinioni.
Pubblicando il tuo scenario nella galleria di GreenFoot lo renderai disponibile a chiunque visiti il sito. Se vuoi condividere il tuo scenario con specifiche persone allora esportalo come applicazione e distribuiscilo per email.
To publish a scenario to the gallery you will need a gallery account. You can create an account by following the link from the gallery homepage or clicking the Create account link at the bottom of the export dialog in Greenfoot. You will need to create an account once, then each time you wish to publish a scenario you enter your username and password in the export dialog.
The Publish page of the export dialog box provides you with fields to enter information to be published with your scenario.
Each scenario on the gallery has an icon, which is part of a sceenshot of the scenario. You can select what that icon should show the Scenario icon box. It shows a picture of the scenario as it is at the moment. You can use the slider next to the box to zoom in and out, and you can drag the image around in the box (after you have zoomed in) to select the exact area you want the icon to show. If you run the scenario and pause it in the middle, then your icon can show what the scenario looks like while it is running, which is useful if your main actors are not visible in the world at the beginning of the scenario.
Enter a title for your scenario, a short description and a full description. The short description will be shown next to your scenario when it is displayed in a list, such as a search results page. The full description will be displayed above your scenario on the gallery, and can include an explaination and instructions for using the scenario. If you have your own webpage about this scenario you can enter its URL to provide a link to it on the gallery.
The Greenfoot gallery organises scenarios by means of tags. Select some of the commonly used tags if they are relevant to your scenario, and add any tags of your own. Tags should usually be one word long, or a small number of words connected by hyphens, and each tag should be typed on a new line in the textbox. Have a look at the tag cloud on the homepage of the gallery for ideas about what tags might be appropriate. It is always a good idea to re-use tags that other authors have already used so that similar scenarios can be grouped together.
The popular tags provided for you in the export dialog are:
For demonstrations of Greenfoot features or new ways to do things in Greenfoot
For simulatons of real-world situations, such as behaviour of swarms or the workings of a machine
For scenarios which use mouse input
For scenarios which use some sort of Graphical User Interface (such as buttons, dialogs, sliders and other application-like input)
There are two additional options which you can select for your scenario. If you check the Publish source code check box then other users of the gallery will be able to download your scenario to see its source code, and play around with it on their computers (however that will not affect the version on the gallery). If you select this option your scenario will have the with-source tag added to it when it is published.
The Lock scenario option allows you to prevent users of your scenario from changing the speed of execution and dragging objects around the world before the scenario is run. If you uncheck this box then users will be able to move your actors around and change the speed, as is possible in Greenfoot itself.
Once you have filled in all the details, make sure you have entered your username and password and click the Export button to publish your scenario to the gallery. If you click Cancel then the details you have entered will be saved ready for when you do want to export it.
Esportare lo scenario come pagina web
Per esportare uno scenario come pagina web seleziona la sezione Pagina web nella finestra di dialogo di esportazione. Seleziona una cartella dove salvare la pagina web e clicca su Esporta.
Attivando la casella Blocca lo scenario impedirai agli utenti dello scenario di cambiare la velocità di esecuzione e di trascinare gli oggetti nel mondo prima che lo scenario sia in esecuzione. Se disattivi la casella allora gli utenti potranno spostare gli oggetti in giro e cambiare la velocità, come in Greenfoot.
Nota che l’esportazione dello scenario come pagina web non pubblicherà lo scenario sul web, ma ti permetterà soltanto divedere lo scenario in un browser web. Per pubblicare lo scenario sul web (se non hai un tuo sito) utilizza la sezione Pubblicadella finestra di dialogo e pubblicherai lo scenario nella galleria di Greenfoot. Per pubblicare lo scenario sul tuo sito esportalo come pagina web e poi carica i file .html e .jar sul tuo server web.
Esportare lo scenario come applicazione
Per esportare uno scenario come applicazione seleziona la sezione Applicazione nella finestra di dialogo di esportazione. Seleziona una cartella dove salvare l’applicazione, scegli se vuoi bloccare o meno lo scenario e clicca su Esporta.
Attivando la casella Blocca lo scenario impedirai agli utenti dello scenario di cambiare la velocità di esecuzione e di trascinare gli oggetti nel mondo prima che lo scenario sia in esecuzione. Se disattivi la casella allora gli utenti potranno spostare gli oggetti in giro e cambiare la velocità, come in Greenfoot.
L’applicazione creata sarà un file eseguibile .jar. I computer con installata la versione corretta di Java dovrebbero lanciare l’applicazione. Per la maggior parte di essi, basterà fare doppio clic sul file .jar per lanciarlo. Se il computer non è impostato per farlo, potrai utilizzare il comando seguente, da linea di comando, per lanciare lo scenario:
Sostituisci il nome Scenario.jar con il nome del tuo file.