// This is my favorite game, I understand it.
// this is version II
// John Sklar for CEd 516 - Spring, 2000
// converted to swing Feb, 2003
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Jguessnumber extends JApplet implements ActionListener
{
// initialize the variables
final int TOP=100;
int number,min,max,tries;
Font VerybigFont = new Font("Helvetica",Font.BOLD,30);
Font bigFont = new Font("Helvetica",Font.BOLD,24);
JButton aButton = new JButton("Guess the Number");
JLabel Prompt = new JLabel(" Guess a number from " + min + " to " + TOP+ " ");
JLabel Hint = new JLabel("Type your guess");
JTextField aGuess = new JTextField(3);
JPanel top,middle,bottom;
public void init()
{
// set all the fonts, add the components
getContentPane().setLayout(new GridLayout(3,1));
top = new JPanel();
top.setBackground(Color.white);
Prompt.setForeground(Color.blue);
middle = new JPanel();
middle.setBackground(Color.blue);
bottom = new JPanel();
bottom.setBackground(Color.black);
bottom.setForeground(Color.black);
// set all the fonts
aButton.setFont(bigFont);
Prompt.setFont(VerybigFont);
aGuess.setFont(bigFont);
Hint.setFont(bigFont);
Hint.setForeground(Color.white);
// add the panels
getContentPane().add(top);
getContentPane().add(middle);
getContentPane().add(bottom);
//put stuff in the panels
top.add(Prompt);
middle.add(Hint);
middle.add(aGuess);
bottom.add(aButton);
// set some stuff up.
aButton.addActionListener(this);
aGuess.addActionListener(this);
setSize(500,155);
}
public void start()
{ // set up the game
min=1;
max=TOP;
tries=0;
number = (int)(1+((Math.random()*TOP)));
Prompt.setText("Guess a number from " + min + " to " + max);
aGuess.setText("");
Hint.setText("Type a guess");
aButton.setText("Guess the Number");
aGuess.setText("");
aGuess.grabFocus();
invalidate();
validate();
}
public void actionPerformed(ActionEvent e)
{
// sort out the two buttons, thanks Gen Lan
if (aButton.getText()=="Play Again?")
start();
else {
tries++;
int guess = Integer.parseInt(aGuess.getText());
if(guess < number){
if(guess >0)
min = guess;
Hint.setText("Too Small...");
}
else
if(guess > number){
if(guess < TOP)
max = guess;
Hint.setText("Too Big...");
}
else
if(guess==number){
if(tries>1)
Prompt.setText("You guessed " + number + " in " + tries + " guesses!");
else
Prompt.setText("You guessed " + number + " in " + tries + " guess!");
Hint.setText("You Got it.");
aButton.setText("Play Again?");
}
if(guess!=number)
{
Prompt.setText("Guess a number from " + min + " to " + max);
aGuess.setText("");
invalidate();
validate();
}
}
}
}