Java Reference
In-Depth Information
g.translate (getWidth() / 2, getHeight() / 2);
g.setColor (255, 255, 255 - javagochi.getHappiness() * 25);
g.fillArc (- width / 2, - height / 2, width, height, 0, 360);
g.setColor (0, 0, 0);
g.drawArc (- width / 2, - height / 2, width, height, 0, 360);
}
}
In order to simplify the centered display of the Javagochi , you set the origin of the coordinate
system to the center of the screen using the translate() method. The outline of the Javagochi 's
face is then drawn using the drawArc() method.
Unfortunately, the outline of the Javagochi looks a bit boring, so you will add a simple face now. In
order to avoid duplicated code, you put the drawing of the eyes in a separate method. The drawEye()
method takes the Graphics object, the coordinates of the eye, and a size parameter:
void drawEye (Graphics g, int x, int y, int size) {
if (javagochi.isDead()) {
graphics.drawLine (x - size/2, y, x + size/2, y);
graphics.drawLine (x, y - size/2, x, y + size/2);
}
else
graphics.drawArc (x-size/2, y-size/2, size, size, 0, 360);
}
Now you can insert the rest of the drawing code into the paint() method, just after drawArc() .
You will start with the eyes by calling the drawEye() method defined previously. By using fractions
of the current width and height of the Javagochi , the eyes are positioned and sized correctly:
drawEye (g, - width / 6, - height / 5, height / 15 + 1);
drawEye (g, width / 6, - height / 5, height / 15 + 1);
Now you draw the mouth, depending on the current happiness of the Javagochi . Again, you use
fractions of the Javagochi size for positioning and sizing:
switch (javagochi.getHappiness() / 3) {
case 0:
case 1: g.drawArc (-width/6, height/7, width/3, height/6, 0, 180);
break;
case 2: g.drawLine (-width/6, height/7, width/6, height/7); break;
default: g.drawArc (-width/6, height/7, width/3, height/6, 0, -180);
}
Simple Interaction
When you run the first version of the Javagochi application, the Javagochi starts out happy, but
dies quickly from starvation. Obviously, you need a way to transfer energy from the device's battery to
the Javagochi . One possibility would be to add a corresponding command.
However, in the " High-Level API " section you learned that commands may be delegated to a sub-menu.
When the Javagochi urgently needs feeding, you would like to be able to react quickly.
So you just use the key event corresponding to the game action FIRE for feeding the Javagochi :
Search WWH ::




Custom Search