scg/ch10/Hangman

From FANG

Jump to: navigation, search

001 package scg.ch10;
002 
003 import java.io.File;
004 import java.io.FileNotFoundException;
005 import java.net.URL;
006 import java.util.ArrayList;
007 import java.util.Scanner;
008 
009 import fang2.core.Game;
010 import fang2.sprites.StringSprite;
011 import fang2.util.InitializeApplication;
012 
013 /**
014  * The Hangman game: During {@code #setup()} a word is generated as are
015  * all the appropriate sprites (score, alphabet selector, hangman, show
016  * word). Game runs with player selecting the letters and the hangman
017  * and show word updating (show word updates if the letter _is_ in the
018  * word; the hangman is updated if the letter _is not_ in the word).
019  Level ends when the player is hung _or_ the word is guessed.
020  */
021 public class Hangman
022   extends Game {
023   /** the alphabet selector on the screen */
024   AlphabetSelector alphabet;
025 
026   /** represents the hangman (gallows and body) */
027   HangmanSprite hangman;
028 
029   /** sprite representing the score */
030   ScoreSprite scoreSprite;
031 
032   /** the list of possible phrases to choose for the player to guess */
033   ArrayList<String> phrases = null;
034 
035   /** sprite representing the show word */
036   GuessableWord gamePhrase;
037 
038   /**
039    * Advance one frame: if game continues, check for selected letter; if
040    * letter is not null character, guess letter in the word to be
041    * guessed; if guess is not good, add a body part to the hangman
042    * sprite and if hangman is dead expose word and end game; if guess
043    * was good, check if word is guessed and if it is, game over. If game
044    * does not continue, keep checking for a press of the spacebar. When
045    * it is pressed, restart the game.
046    */
047   @Override
048   public void advance(double dT{
049     if (isGameOver()) {
050       if (getKeyPressed() == ' '{
051         setGameOver(false);
052         startOver();
053       }
054     } else {
055       char ch = alphabet.selectedChar();
056       if (ch != '\0'{
057         if (gamePhrase.guess(ch)) {
058           if (gamePhrase.isGuessed()) {
059             scoreSprite.win();
060             doneWithGame("Congratulations");
061           }
062         } else {
063           hangman.incrementState();
064           if (hangman.isDead()) {
065             gamePhrase.expose();
066             gamePhrase.setColor(getColor("red"));
067             scoreSprite.lose();
068             doneWithGame("You lose!");
069           }
070         }
071       }
072     }
073   }
074 
075   /**
076    * Setup the sprites: the alphabet selector, the hangman, the score,
077    * and the word.
078    */
079   @Override
080   public void setup() {
081     setupAlphabet();
082     setupHangman();
083     setupScore();
084     setupGamePhrase();
085   }
086 
087   /**
088    * Done with the game. Display an end of game message on the screen
089    * and append instructions on how to restart the game.
090    *
091    @param  endOfGameMessage  the end of game message to display for
092    *                           the player
093    */
094   private void doneWithGame(String endOfGameMessage{
095     StringSprite restartMessage = new StringSprite(endOfGameMessage +
096         "\nPress <space> to play again.");
097     restartMessage.setScale(0.9);
098     restartMessage.setLocation(0.50.75);
099     addSprite(restartMessage);
100     alphabet.hide();
101     setGameOver(true);
102   }
103 
104   /**
105    * Get the name of the word file. If there are named arguments, it is
106    * the argument named "words". (This is the case for applets, for
107    * example.) If there is no named argument words, get the first
108    * unnamed argument. If there are no unnamed arguments, punt (return
109    default name).
110    *
111    @return  name of the word file (default or otherwise)
112    */
113   private String getFname() {
114     // try to use the named parameter from the applet/application
115     String name = getParameter("words");
116 
117     if (name != null{
118       return name;
119     }
120     // try to use the unnamed parameter from the application
121     ArrayList<String> args = InitializeApplication.getUnnamedArgs();
122     if (args.size() 0{
123       return args.get(0);
124     } else {
125       // give up - we don't have a file name
126       return "phrases.txt";
127     }
128   }
129 
130   /**
131    * Null the {@link #phrases} field. If fname is non-nulltry opening
132    * it as a {@link File}. If that throws an exception (there is a
133    * problem) attempt to use the name as an {@link URL} name to get a
134    {@link Game} resource (used for on-line applets).
135    *
136    <p>If either approach properly opens the {@link Scanner} read the
137    * file line by line. Each line goes into {@link #phrases}.
138    *
139    <p>If neither approach works, the method prints an appropriate
140    * error message about not being able to open the named file/URL and
141    * leaves phrases == null.
142    *
143    @param  fname  the file to read; null means no file name specified
144    */
145   private void listLoadFromFile(String fname{
146     phrases = null;
147     if (fname != null{
148       Scanner scanner = null;
149       try {
150         File file = new File(fname);
151         if (file.exists() && file.canRead()) {
152           scanner = new Scanner(file);
153         }
154       } catch (Exception e{
155         URL url = Game.getGameResource(fname);
156         try {
157           scanner = new Scanner(url.openStream());
158         } catch (Exception e1{
159           System.out.println(
160             "There was an error reading the word file.");
161           System.out.println(
162             "  Make sure to include the path to a word file.");
163           System.out.println(
164             "  Make sure file exists and is readable.");
165         }
166       }
167 
168       if (scanner != null{
169         ArrayList<String> localStrings = new ArrayList<String>();
170         String line;
171         while (scanner.hasNextLine()) {
172           line = scanner.nextLine();
173           if (line.length() 0{
174             localStrings.add(line.toLowerCase());
175           }
176         }
177         phrases = localStrings;
178         scanner.close();
179       }
180     }
181 
182     if (phrases == null{
183       System.out.println("There was an error reading the word file.");
184       System.out.println(
185         "  Make sure to include the path to a word file.");
186       System.out.println("  Make sure file exists and is readable.");
187       System.exit(1);
188     }
189   }
190 
191   /**
192    * Setup the alphabet selector sprite. Almost as wide as the screen,
193    * centered in bottom half of the screen.
194    */
195   private void setupAlphabet() {
196     alphabet = new AlphabetSelector();
197     alphabet.setScale(0.85);
198     alphabet.setLocation(0.50.75);
199     addSprite(alphabet);
200   }
201 
202   /**
203    * Setup the hangman sprite. Centered in top half of the screen.
204    */
205   private void setupHangman() {
206     hangman = new HangmanSprite();
207     hangman.setLocation(0.50.25);
208     hangman.setScale(0.5);
209     hangman.setColor(getColor("misty rose"));
210     addSprite(hangman);
211   }
212 
213   /**
214    * Setup the score sprite in the upper left corner of the screen.
215    */
216   private void setupScore() {
217     scoreSprite = new ScoreSprite();
218     scoreSprite.leftJustify();
219     scoreSprite.topJustify();
220     scoreSprite.setLocation(0.00.0);
221     scoreSprite.setScale(0.1);
222     addSprite(scoreSprite);
223   }
224 
225   /**
226    * Setup the guessable word in the center of the screen. Calls {@link
227    * #pickPhrase()} to get the value to play.
228    */
229   private void setupGamePhrase() {
230     String pickedPhrase = pickPhrase();
231     gamePhrase = new GuessableWord(pickedPhrase);
232     gamePhrase.bottomJustify();
233     gamePhrase.setWidth(0.7);
234     gamePhrase.setLocation(0.50.6);
235     addSprite(gamePhrase);
236   }
237 
238   /**
239    * Load a selection of phrase and return one, the word to be guessed.
240    *
241    @return  the phrase to be guessed
242    */
243   private String pickPhrase() {
244     if ((phrases == null|| phrases.isEmpty()) {
245       listLoadFromFile(getFname());
246     }
247     if (phrases == null{
248       return "cats and dogs";//
249     }
250     int phraseNdx = randomInt(0, phrases.size());
251     return phrases.remove(phraseNdx);
252   }
253 }
254 
255 //Uploaded on Mon Mar 29 21:40:46 EDT 2010


Download/View scg/ch10/Hangman.java





Views
Personal tools
Add to 
del.icio.usAdd to 
diggAdd to 
FacebookAdd to 
favoritesAdd to 
GoogleAdd to 
MySpaceAdd to 
PrintAdd to 
SlashdotAdd to 
StumbleUponAdd to 
Twitter

Games
Games