Java Reference
In-Depth Information
static final int IDEAL_WEIGHT = 100;
Display display = Display.getDisplay (this);
Face face = new Face (this);
int weight = IDEAL_WEIGHT;
Timer consumption;
int score;
Before you begin development, let us first say a few words about the Javagochi itself. A
Javagochi has a weight that is initialized with its IDEAL_WEIGHT . It also owns an instance of
Display , Face , and Consumption , which will be explained later. Finally, it stores a score value
for the care the owner spends on the Javagochi .
The happiness of the Javagochi is determined by the deviation of its current weight from the ideal
weight, ranging from 10 to 0:
public int getHappiness() {
return 20 - (weight > IDEAL_WEIGHT
? 10 * weight / IDEAL_WEIGHT
: 10 * IDEAL_WEIGHT / weight);
if (happiness < 0) happiness = 0;
if (happiness > 10) happiness = 10;
}
This formula also demonstrates how to circumvent problems with the absence of floating point
arithmetic. In order to avoid loss of significant fractions, the values are scaled up before division.
Like all other known life forms, the Javagochi can die. Javagochi es only die from sadness when
their happiness level reaches zero:
public boolean isDead() {
return getHappiness <= 0;
}
The only other action a Javagochi can perform besides dying is to transform energy to matter and
back. Since a weight change may change the Javagochi 's look, a repaint is requested in the
transform() method:
public void transform (int amount) {
if (!isDead()) {
weight += amount;
face.repaint();
}
}
When the Javagochi MIDlet is started, it displays itself and starts a consumption Timer that keeps
track of the power the Javagochi needs for living:
public void startApp() {
display.setCurrent (face);
consumption = new Consumption (this).start();
}
When the MIDlet is paused, the Javagochi goes to sleep by telling the consumption thread to
terminate itself. The destroyApp() method does nothing because the life cycle will enter sleep
anyway, and no further cleanup is needed:
public void pauseApp() {
Search WWH ::




Custom Search