Sometimes, it is necessary to give the users some information regarding which type of (key) input is accepted by our scenario.
As an example, let us consider the extended lunarlander scenario. Well, I call this "extended" because I've made several modifications by extending the behavior of the Lander, i.e. it can perform several flight/landing modes which are determined by user inputs. These modifications are addressed in the book and might be discussed in this website next time. Below is a screenshot indicating how such "an information screen" is integrated to the scenario.

Displaying information for the lunarlander scenario
Step 1 : create an image containing the information you want to show and place it in the "images" subfolder of the lunarlander scenario. We will use this as the class image of the "information screen".
Step 2 : create a subclass from Actor, name it as you like and associate it with the image created in step 1 above.
Step 3 : edit the new Actor (here I call it InfoImage) and copy the following codes (explanation at the end).
public class InfoImage extends Actor
{
private boolean active = true;
public InfoImage() { act(); }
public void act() {
if(active) {
Greenfoot.stopSimulation();
active = false;
}
}
public void setActive(boolean val){
active = val;
}
public boolean getActive() { return active; }
}
Step 4 : edit the class Lander and add some codes for the corresponding methods below.
public void act()
{
destroyInfo();
processKeys();
// ... original codes
}
private void processKeys() {
// ... original codes
if(Greenfoot.isKeyDown("i")) {
int xlocal = getWorld().getWidth()/2;
int ylocal = getWorld().getHeight()/2;
getWorld().addObject(new InfoImage(),
xlocal, ylocal);
}
}
private void destroyInfo() {
List listvar =
getWorld().getObjects(InfoImage.class);
Iterator i = listvar.iterator();
if(i.hasNext()){
InfoImage varinfo= (InfoImage) i.next();
if(!varinfo.getActive())
getWorld().removeObject(varinfo);
}
}
An InfoImage object is an actor with a simple behavior. It has to exist in the world if it is in an active state. And if it is active, the simulation shall be stopped/paused. This state is saved in the boolean variable state. If it is not in an active state (variable active = false) the object shall be removed from the world.
The object is created as requested e.g. if the user want to see the information. In our case, this event happens when the user types the key "i". It can also be created at the beginning, by putting the following statement in the Moon constructor:
addObject(new InfoImage(), getWidth()/2, getHeight()/2);
The code fragments mentioned in step 4, must not necessarily be added to the class Lander, since Greenfoot calls the act() method from all objects in the world. But in the lunarlander scenario, we do not have many choices, right ? :-)
Webpage Keywords : Java programming, Java game, Greenfoot scenario
No comments:
Post a Comment