01: package dalma.sample.hangman;
02:
03: import java.util.List;
04: import java.util.Random;
05: import java.util.ArrayList;
06: import java.util.Collections;
07: import java.io.BufferedReader;
08: import java.io.InputStreamReader;
09: import java.io.IOException;
10:
11: /**
12: * List of words.
13: *
14: * @author Kohsuke Kawaguchi
15: */
16: public final class WordList {
17:
18: public static final List<String> words;
19:
20: /**
21: * Picks up a random word.
22: */
23: public static String getRandomWord() {
24: int index = new Random().nextInt(words.size());
25: String s = words.get(index);
26: // interleave with ' ' for visibility
27: StringBuilder sb = new StringBuilder();
28: for (int i = 0; i < s.length(); i++) {
29: if (i != 0)
30: sb.append(' ');
31: sb.append(s.charAt(i));
32: }
33: return sb.toString();
34: }
35:
36: /**
37: * Loads the word list.
38: */
39: static {
40: try {
41: List<String> list = new ArrayList<String>();
42:
43: BufferedReader in = new BufferedReader(
44: new InputStreamReader(WordList.class
45: .getResourceAsStream("words.txt")));
46: String line;
47: while ((line = in.readLine()) != null) {
48: list.add(line);
49: }
50:
51: words = Collections.unmodifiableList(list);
52: } catch (IOException e) {
53: throw new Error(e); // treat this as a fatal error
54: }
55: }
56: }
|