01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: Game.java 3705 2007-03-28 20:00:24Z gbevin $
07: */
08: package tutorial.numberguess;
09:
10: import com.uwyn.rife.continuations.ContinuationContext;
11: import com.uwyn.rife.engine.Element;
12: import com.uwyn.rife.template.Template;
13:
14: import java.util.Random;
15:
16: /**
17: * This element handles guesses that are being made by participants in a game.
18: * <p>
19: * If a continuation is found, it is resumed and all local variables that
20: * define an active game are restored, otherwise a new game is started.
21: * <p>
22: * The visitor is able to submit a guess through a form. The element validates
23: * the answer and keeps track of the number of guesses. The user receives an
24: * indication about the relation of the correct answer with the last submitted
25: * guess. If the guess was correct, the <code>success</code> exit is activated.
26: *
27: * @author Geert Bevin (gbevin[remove] at uwyn dot com)
28: * @version $Revision: 3705 $
29: */
30: public class Game extends Element {
31: private static Random randomNumbers = new Random();
32:
33: public void processElement() {
34:
35: Template template = getHtmlTemplate("game");
36: int answer = 0, guesses = 0, guess = -1;
37:
38: answer = randomNumbers.nextInt(101);
39: while (guess != answer) {
40: print(template);
41:
42: pause();
43:
44: template.clear();
45:
46: guess = getParameterInt("guess", -1);
47: if (guess < 0 || guess > 100) {
48: template.setBlock("warning", "invalid");
49: continue;
50: }
51: guesses++;
52:
53: if (answer < guess)
54: template.setBlock("msg", "lower");
55: else if (answer > guess)
56: template.setBlock("msg", "higher");
57: }
58:
59: ContinuationContext.getActiveContext().removeContextTree();
60:
61: template = getHtmlTemplate("success");
62: template.setValue("answer", answer);
63: template.setValue("guesses", guesses);
64: print(template);
65: }
66: }
|