Author Archive

Number guess game with continuations

Saturday, November 17th, 2007

We found a nice illustration of using continuations among RIFE examples and wrote the Number guess game also using Aranea Continuations (for the introduction read Aranea and Swing get Continuations).

The following game chooses a random integer between 0 and 100 and lets the user to guess it. Each time a hint is given whether the right answer is higher or lower than the entered:

class NumberGuessingGameExample extends JPanel {

	private static final int MIN = 0;
	private static final int MAX = 100;

	@Resumable
	void init() {
		setLayout(new BorderLayout());

		JLabel label = new JLabel("Guess a number from " + MIN + " to " + MAX);
		JTextField field = new JTextField();
		field.setHorizontalAlignment(JTextField.CENTER);
		JButton button = new JButton("Guess");

		add(label, BorderLayout.NORTH);
		add(field, BorderLayout.CENTER);
		add(button, BorderLayout.SOUTH);
		updateUI();

		int answer = MIN + (int) (Math.random() * (MAX - MIN + 1));
		int guesses = 0;
		int guess = -1;

		while (guess != answer) {
			SwingBlockingUtil.waitForOneAction(button);

			try {
				guess = Integer.parseInt(field.getText());
			} catch (NumberFormatException e) {
				continue;	// ignore
			}

			if (guess < MIN || guess > MAX) {
				continue;	// ignore
			}

			field.setText("");

			if (answer < guess) label.setText("The answer is lower than " + guess);
			if (answer > guess) label.setText("The answer is higher than " + guess);

			guesses++;
		}

		System.out.println("You found the answer " + answer + " by " + guesses + " guesses");
	}

	public static void main(String[] args) {
		NumberGuessingGameExample panel = new NumberGuessingGameExample();
		JFrame frame = new JFrame();
		frame.add(panel);
		panel.init();
	}

}

Notice that the program consists of one main loop which takes a user input, processes it and gives a response. This is like reading standard input. To do the same in Swing, usually one is forced to register an ActionListener and the program flow jumps to that – different method when an action occurs.

Here waitForOneAction() blocks the program flow until the button receives an action (like java.io.Reader.read()).

Under the hood still an ActionListener is used. When waitForOneAction() is invoked a snapshot is taken from the program exceution and when ActionListener.actionPerformed() is reached this snapshot is used to resume the program.

The whole source code can be accessed at:
http://svn.araneaframework.org/repos/aranea-continuations/