KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > echo2tutorial > numberguess > NumberGuessApp


1 /*
2  * This file is part of the Echo Web Application Framework (hereinafter "Echo").
3  * Copyright (C) 2002-2005 NextApp, Inc.
4  *
5  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * Alternatively, the contents of this file may be used under the terms of
18  * either the GNU General Public License Version 2 or later (the "GPL"), or
19  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
20  * in which case the provisions of the GPL or the LGPL are applicable instead
21  * of those above. If you wish to allow use of your version of this file only
22  * under the terms of either the GPL or the LGPL, and not to allow others to
23  * use your version of this file under the terms of the MPL, indicate your
24  * decision by deleting the provisions above and replace them with the notice
25  * and other provisions required by the GPL or the LGPL. If you do not delete
26  * the provisions above, a recipient may use your version of this file under
27  * the terms of any one of the MPL, the GPL or the LGPL.
28  */

29
30 package echo2tutorial.numberguess;
31
32 import nextapp.echo2.app.ApplicationInstance;
33 import nextapp.echo2.app.Button;
34 import nextapp.echo2.app.Color;
35 import nextapp.echo2.app.ContentPane;
36 import nextapp.echo2.app.Extent;
37 import nextapp.echo2.app.Insets;
38 import nextapp.echo2.app.Label;
39 import nextapp.echo2.app.ResourceImageReference;
40 import nextapp.echo2.app.Column;
41 import nextapp.echo2.app.TextField;
42 import nextapp.echo2.app.Window;
43 import nextapp.echo2.app.event.ActionEvent;
44 import nextapp.echo2.app.event.ActionListener;
45 import nextapp.echo2.app.layout.ColumnLayoutData;
46
47 /**
48  * Guess-a-number Tutorial Application.
49  */

50 public class NumberGuessApp extends ApplicationInstance {
51
52     private Window window;
53     
54     /**
55      * Displays a congratulatory message to the user when s/he has guessed
56      * the correct number.
57      *
58      * @param numberOfTries the number of tries it took the user to guess the
59      * correct answer.
60      */

61     void congratulate(int numberOfTries) {
62         window.setContent(new CongratulationsPane(numberOfTries));
63     }
64     
65     /**
66      * @see nextapp.echo2.app.ApplicationInstance#init()
67      */

68     public Window init() {
69         window = new Window();
70         window.setTitle("Echo2 Guess-A-Number");
71         startNewGame();
72         return window;
73     }
74
75     /**
76      * Starts a new game:
77      * Sets content of Window to a new <code>GamePane</code>.
78      */

79     void startNewGame() {
80         // Set the content to be a new GamePane, so the
81
window.setContent(new GamePane());
82     }
83 }
84
85 /**
86  * A <code>ContentPane</code> which generates a random number and provides the
87  * user opportunities to guess it.
88  */

89 class GamePane extends ContentPane
90 implements ActionListener {
91
92     /** Randomly generated number between 1 and 100 inclusive. */
93     private int randomNumber = ((int) Math.floor(Math.random() * 100)) + 1;
94     
95     /** The current lowest sensible guess, based on previous guesses. */
96     private int lowerBound = 1;
97
98     /** The current highest sensible guess, based on previous guesses. */
99     private int upperBound = 100;
100     
101     /** The number of guesses made in the current game. */
102     private int numberOfTries = 0;
103     
104     /** <code>TextField</code> into which guesses are entered. */
105     private TextField guessEntryField;
106     
107     /**
108      * <code>Label</code> displaying the current "status". Initially blank,
109      * this label will inform the user whether his/her last guess was too
110      * high, too low, or simply invalid.
111      */

112     private Label statusLabel = new Label();
113     
114     /**
115      * <code>Label</code> indicating the total number of guesses made so far.
116      */

117     private Label countLabel = new Label("You have made no guesses.");
118     
119     /**
120      * <code>Label</code> prompting the user to enter a new guess. The text of
121      * this label will change as the user makes guesses to reflect the updated
122      * "sensible" range of possible guesses.
123      */

124     private Label promptLabel = new Label("Guess a number between 1 and 100: ");
125     
126     /**
127      * Creates a new <code>GamePane</code>.
128      */

129     GamePane() {
130         super();
131         
132         Column layoutColumn = new Column();
133         layoutColumn.setInsets(new Insets(30));
134         layoutColumn.setCellSpacing(new Extent(10));
135         add(layoutColumn);
136         
137         layoutColumn.add(new Label(new ResourceImageReference("/echo2tutorial/numberguess/TitleBanner.png")));
138         layoutColumn.add(statusLabel);
139         layoutColumn.add(countLabel);
140         layoutColumn.add(promptLabel);
141         
142         guessEntryField = new TextField();
143         
144         guessEntryField.setForeground(Color.WHITE);
145         guessEntryField.setBackground(Color.BLUE);
146         ColumnLayoutData columnLayoutData = new ColumnLayoutData();
147         columnLayoutData.setInsets(new Insets(20, 0));
148         guessEntryField.setLayoutData(columnLayoutData);
149         layoutColumn.add(guessEntryField);
150         
151         Button submitButton = new Button("Submit Your Guess");
152         submitButton.setActionCommand("submit guess");
153         submitButton.setForeground(Color.BLACK);
154         submitButton.setBackground(Color.GREEN);
155         submitButton.setWidth(new Extent(200));
156         submitButton.addActionListener(this);
157         layoutColumn.add(submitButton);
158         
159         Button newGameButton = new Button("Start a New Game");
160         newGameButton.setActionCommand("new game");
161         newGameButton.setForeground(Color.WHITE);
162         newGameButton.setBackground(Color.RED);
163         newGameButton.setWidth(new Extent(200));
164         newGameButton.addActionListener(this);
165         layoutColumn.add(newGameButton);
166     }
167     
168     /**
169      * @see nextapp.echo2.app.event.ActionListener#actionPerformed(nextapp.echo2.app.event.ActionEvent)
170      */

171     public void actionPerformed(ActionEvent e) {
172         if (e.getActionCommand().equals("new game")) {
173             ((NumberGuessApp) ApplicationInstance.getActive()).startNewGame();
174         } else if (e.getActionCommand().equals("submit guess")) {
175             processGuess();
176         }
177     }
178     
179     /**
180      * Processes a user's guess.
181      */

182     private void processGuess() {
183         
184         int guess;
185         try {
186             guess = Integer.parseInt(guessEntryField.getDocument().getText());
187         } catch (NumberFormatException JavaDoc ex) {
188             statusLabel.setText("Your guess was not valid.");
189             return;
190         }
191
192         ++numberOfTries;
193
194         if (guess == randomNumber) {
195             ((NumberGuessApp) ApplicationInstance.getActive()).congratulate(numberOfTries);
196             return;
197         }
198         
199         if (guess < 1 || guess > 100) {
200             statusLabel.setText("Your guess, " + guess + " was not between 1 and 100.");
201         } else if (guess < randomNumber) {
202             if (guess >= lowerBound) {
203                 lowerBound = guess + 1;
204             }
205             statusLabel.setText("Your guess, " + guess + " was too low. Try again:");
206         } else if (guess > randomNumber) {
207             statusLabel.setText("Your guess, " + guess + " was too high. Try again:");
208             if (guess <= upperBound) {
209                 upperBound = guess - 1;
210             }
211         }
212
213         // Update number of tries label.
214
if (numberOfTries == 1) {
215             countLabel.setText("You have made 1 guess.");
216         } else {
217             countLabel.setText("You have made " + numberOfTries + " guesses.");
218         }
219         
220         // Update the prompt label to reflect the new sensible range of numbers.
221
promptLabel.setText("Guess a number between " + lowerBound + " and " + upperBound + ": ");
222     }
223 }
224
225 /**
226  * A <code>ContentPane</code> which presents a congratulatory message to the
227  * player when the correct number has been guessed.
228  */

229 class CongratulationsPane extends ContentPane
230 implements ActionListener {
231
232     /**
233      * Creates a new <code>CongratulationsPane</code>.
234      *
235      * @param numberOfTries the number of tries it took the user to guess the
236      * correct answer.
237      */

238     CongratulationsPane(int numberOfTries) {
239         Column layoutColumn = new Column();
240         layoutColumn.setInsets(new Insets(30));
241         layoutColumn.setCellSpacing(new Extent(30));
242         add(layoutColumn);
243         
244         layoutColumn.add(new Label(new ResourceImageReference("/echo2tutorial/numberguess/CongratulationsBanner.png")));
245         layoutColumn.add(new Label("You got the correct answer in " + numberOfTries + (numberOfTries == 1 ? " try." : " tries.")));
246
247         Button button = new Button("Play Again");
248         button.setForeground(Color.WHITE);
249         button.setBackground(Color.RED);
250         button.setWidth(new Extent(200));
251         button.addActionListener(this);
252         layoutColumn.add(button);
253     }
254
255     /**
256      * @see nextapp.echo2.app.event.ActionListener#actionPerformed(nextapp.echo2.app.event.ActionEvent)
257      */

258     public void actionPerformed(ActionEvent e) {
259         ((NumberGuessApp) ApplicationInstance.getActive()).startNewGame();
260     }
261 }
262
Popular Tags