home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java by Example
/
jbecd.bin
/
JBE-CD
/
NTUsers
/
JBECODE.ZIP
/
JavaByExample
/
chap12
/
GuessApplet.java
< prev
next >
Wrap
Text File
|
1996-02-13
|
2KB
|
91 lines
import java.awt.*;
import java.applet.*;
import java.lang.Math;
public class GuessApplet extends Applet
{
///////////////////////////////////////
// Data fields.
///////////////////////////////////////
TextField textField1;
int guesses;
int number;
////////////////////////////////////////
// Overridden methods.
////////////////////////////////////////
public void init()
{
textField1 = new TextField(10);
add(textField1);
textField1.setText("50");
guesses = 0;
number = CreateNumber();
}
public void paint(Graphics g)
{
DrawInstructions(g);
int guess = GetGuess();
ShowMessage(g, guess);
}
public boolean action(Event event, Object arg)
{
++guesses;
repaint();
return true;
}
////////////////////////////////////////
// Private methods.
////////////////////////////////////////
void DrawInstructions(Graphics g)
{
g.drawString("Try to guess the number I am", 48, 65);
g.drawString("thinking of. The number will be", 48, 80);
g.drawString("between 0 and 100. You have an", 48, 95);
g.drawString("unlimited number of tries.", 48, 110);
g.drawString("Good Luck.", 95, 140);
}
int GetGuess()
{
String s = textField1.getText();
int num = Integer.parseInt(s);
return num;
}
int CreateNumber()
{
float n = (float)Math.random();
number = (int)(n * 100 + 1);
return number;
}
void ShowMessage(Graphics g, int guess)
{
String s = "Guesses so far: ";
s += String.valueOf(guesses);
g.drawString(s, 80, 170);
if (guess < number)
g.drawString("Your guess is too low.", 70, 185);
else if (guess > number)
g.drawString("Your guess is too high.", 70, 185);
else
{
g.drawString("You guessed the number!", 65, 185);
g.drawString("But I just picked a new one.", 65, 200);
StartNewGame();
}
}
void StartNewGame()
{
number = CreateNumber();
textField1.setText("50");
guesses = 0;
}
}