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: Guess.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package tutorial.numberguess;
09:
10: import com.uwyn.rife.engine.Element;
11: import com.uwyn.rife.template.Template;
12: import tutorial.numberguess.backend.Contest;
13: import tutorial.numberguess.backend.Game;
14:
15: /**
16: * This element handles guesses that are being made by participants in a game.
17: * <p>
18: * If an active game is detected, it is resumed. Otherwise, a new game is
19: * started.
20: * <p>
21: * The visitor is able to submit a guess through a form. The element validates
22: * the answer and keeps track of the number of guesses. The user receives an
23: * indication about the relation of the correct answer with the last submitted
24: * guess. If the guess was correct, the <code>success</code> exit is activated.
25: *
26: * @author Geert Bevin (gbevin[remove] at uwyn dot com)
27: * @version $Revision: 3634 $
28: */
29: public class Guess extends Element {
30: private Game game;
31:
32: private String gameid;
33: private int guess = -1;
34:
35: public void setGameid(String gameid) {
36: this .gameid = gameid;
37: }
38:
39: public void setGuess(int guess) {
40: this .guess = guess;
41: }
42:
43: /**
44: * An instance of the template that's being used by the element instance.
45: */
46: private Template template;
47:
48: /**
49: * The element's initialization.
50: */
51: public void initialize() {
52: // obtain the active game
53: game = Contest.getGame(gameid);
54: // if no game could be found, start a new one
55: if (null == game) {
56: exit("start");
57: }
58:
59: // retrieve the html template
60: template = getHtmlTemplate("guess");
61: }
62:
63: /**
64: * The element's entry point.
65: */
66: public void processElement() {
67: // output the template
68: print(template);
69: }
70:
71: /**
72: * Processes a guess when the form has been submitted.
73: */
74: public void doPerformGuess() {
75: // validate the guess
76: if (guess < 0 || guess > 100) {
77: // if the guess was invalid, a warning is shown and the logic is
78: // interrupted
79: template.setBlock("warning", "invalid");
80: } else {
81: // increase the number of guess attempts
82: game.increaseGuesses();
83:
84: // check the correctness of the guess in case of a successful match, the
85: // success exit is triggered, otherwise an indication message is shown
86: if (game.getAnswer() < guess) {
87: template.setBlock("indication", "lower");
88: } else if (game.getAnswer() > guess) {
89: template.setBlock("indication", "higher");
90: } else {
91: setOutput("gameid", gameid);
92: exit("success");
93: }
94: }
95:
96: // output the template
97: print(template);
98: }
99: }
|