KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hangman > WordSource


1 /* This work is hereby released into the Public Domain.
2  * To view a copy of the public domain dedication, visit
3  * http://creativecommons.org/licenses/publicdomain/
4  * or send a letter to Creative Commons, 559 Nathan Abbott Way,
5  * Stanford, California 94305, USA.
6  */

7
8
9 package hangman;
10
11 import java.io.FileReader JavaDoc;
12 import java.io.IOException JavaDoc;
13 import java.io.LineNumberReader JavaDoc;
14 import java.io.Reader JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Collections JavaDoc;
17 import java.util.List JavaDoc;
18
19 import Jmc.baseTools.*;
20
21 /**
22  *
23  * Used by {@link hangman1.Game} to obtain a a random word.
24  *
25  * @author Howard Lewis Ship (original Tapestry version)
26  * @author Dirk von der Weiden (WidgetServer version)
27  */

28
29 public class WordSource
30 {
31     private int _nextWord;
32     private List JavaDoc _words = new ArrayList JavaDoc();
33
34     public WordSource()
35     {
36         readWords();
37     }
38
39     private void readWords()
40     {
41
42         try
43         {
44               // Changed to find the file
45
Reader JavaDoc r = new FileReader JavaDoc(base_environment.pcmf_getRootDir() + "WordList.txt");
46             LineNumberReader JavaDoc lineReader = new LineNumberReader JavaDoc(r);
47
48             while (true)
49             {
50                 String JavaDoc line = lineReader.readLine();
51
52                 if (line == null)
53                     break;
54
55                 if (line.startsWith("#"))
56                     continue;
57
58                 String JavaDoc word = line.trim().toLowerCase();
59
60                 if (word.length() == 0)
61                     continue;
62
63                 _words.add(word);
64             }
65
66             lineReader.close();
67         }
68         catch (IOException JavaDoc ex)
69         {
70             throw new RuntimeException JavaDoc("Unable to read list of words from file WordList.txt.", ex);
71         }
72
73         // Randomize the word order
74

75         Collections.shuffle(_words);
76
77     }
78
79     /**
80      * Gets the next random word from the list. Once the list is exhausted, it
81      * is shuffled and the first word is taken; this ensures that the user won't
82      * see a repeat word until all words in the list have been played.
83      *
84      **/

85
86     public String JavaDoc nextWord()
87     {
88         if (_nextWord >= _words.size())
89         {
90             _nextWord = 0;
91             Collections.shuffle(_words);
92         }
93
94         return (String JavaDoc) _words.get(_nextWord++);
95     }
96 }
Popular Tags