2

我正在尝试做一个刽子手游戏,我想不出一种将单词存储在数组中并将其与用户输入进行比较的方法。

我使用了一个缓冲阅读器,一个随机发生器,它可以工作,它随机化单词并显示它们。

public static void main(String[] args) {

    FileInputStream textFile;
    BufferedReader readWords;

    // Creates a string array
    ArrayList<String> arrayWordList = new ArrayList<String>();

    // Read in the text file and randomize the words

    try {
        textFile = new FileInputStream("dictionary.txt");
        readWords = new BufferedReader(new InputStreamReader(textFile));
        String line = readWords.readLine();
        while (line != null) {
            arrayWordList.add(line);
            line = readWords.readLine();
        }
        textFile.close();
    } catch (Exception e) {

    }

    Random rand = new Random();
    int arrayIntNumber = rand.nextInt(arrayWordList.size());

    // Initialize the GUI
    new HangGUI();

    System.out.println(arrayWordList.get(arrayIntNumber));

}

我想我应该添加一个 keylistener 并将正确的字母存储在一个 char 或一个字符串数组中,我不确定......

然后我需要将包含正确单词的字符串数组转换为字符串,然后使用我猜的 charAt(i) 将字符串与用户输入的字母进行比较?

这是我为刽子手设计的 GUI 类:

public class HangGUI extends JFrame {
JPanel panel, guessLeftPanel, statusPanel, guessPanel, missPanel;
JLabel guessLeftLabel, guessCountLabel, currentStatus, guess, misses;
JTextField statusText, guessText, missesText;

// Create two arrays
String[] arrayRightWord;
String[] arrayHiddenWord;

String[] getGuess = new String[1];
String missedGuesses = "";


public HangGUI() {

    /* GUI */

    // Creates the menu bar
    JMenuBar menuBar = new JMenuBar();

    // Creates the game menu and add it to the game menu
    JMenu gameMenu = new JMenu("Game");
    menuBar.add(gameMenu);

    // Creates the game menu, the items and add it to the menu's
    JMenuItem startGame = new JMenuItem("Start");

    JMenuItem quitGame = new JMenuItem("Quit");
    gameMenu.add(startGame);
    gameMenu.add(quitGame);

    // Creates the options menu and add it to the menu bar
    JMenu optionsMenu = new JMenu("Options");
    menuBar.add(optionsMenu);

    // Creates a button group consisting of radio buttons and add it to the
    // options menu
    ButtonGroup radioButtons = new ButtonGroup();
    JRadioButton easy = new JRadioButton("Easy");
    JRadioButton medium = new JRadioButton("Medium");
    JRadioButton hard = new JRadioButton("Hard");

    radioButtons.add(easy);
    radioButtons.add(medium);
    radioButtons.add(hard);
    optionsMenu.add(easy);
    optionsMenu.add(medium);
    optionsMenu.add(hard);

    // Creates the main panel
    panel = new JPanel(new GridLayout(4, 1, 5, 5));
    // Creates the label's and textfield's
    // Creates guesses left panel, label and text field
    guessLeftPanel = new JPanel(new GridLayout(1, 2, 5, 5));
    guessLeftLabel = new JLabel("Guesses left: ");
    guessCountLabel = new JLabel();

    // guessCountLabel.setText("sss");

    // ActionListener that doesn't do anything at the moment
    easy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int difficulty = 10;
            guessCountLabel.setText("" + difficulty);
        }
    });

    // ActionListener that doesn't do anything at the moment
    medium.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int difficulty = 7;
            guessCountLabel.setText("" + difficulty);
        }
    });

    // ActionListener that doesn't do anything at the moment
    hard.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int difficulty = 5;
            guessCountLabel.setText("" + difficulty);
        }
    });

    // Creates Current status panel and texfield
    statusPanel = new JPanel(new GridLayout(1, 2, 0, 0));
    currentStatus = new JLabel("Current status: ");
    statusText = new JTextField();
    statusText.setEditable(false);

    /*
     * createRightWord(arrayRandom());
     * 
     * 
     * statusText.setText(returnHiddenWordtoString());
     */

    // Creates the Guess panel and text field
    guessPanel = new JPanel(new GridLayout(1, 2, 0, 0));
    guess = new JLabel("Guess: ");
    guessText = new JTextField();
    guessText.setDocument(new JTextFieldLimit(1));

    // Creates the Misses panel and text field
    missPanel = new JPanel(new GridLayout(1, 2, 0, 0));
    misses = new JLabel("Misses: ");

    missesText = new JTextField();
    missesText.setEditable(false);
    // Make the label's, textfield's, menu and panel visible
    add(menuBar);
    add(panel);

    guessLeftPanel.add(guessLeftLabel);
    guessLeftPanel.add(guessCountLabel);
    statusPanel.add(currentStatus);
    statusPanel.add(statusText);
    guessPanel.add(guess);
    guessPanel.add(guessText);
    missPanel.add(misses);
    missPanel.add(missesText);

    panel.add(guessLeftPanel);
    panel.add(statusPanel);
    panel.add(guessPanel);
    panel.add(missPanel);
    pack();
    setVisible(true);

    // Creates the frame and sets the menu bar
    setSize(400, 200);
    setTitle("Hangman");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setJMenuBar(menuBar);

    /*
     * guessHandler guesshandler = new guessHandler();
     * guessText.addActionListener(guesshandler);
     */

    // Construct a new class that handles Quit's the game
    quitHandler quithandler = new quitHandler();
    quitGame.addActionListener(quithandler);

    // Construct a new class that handles Starting the game
    startHandler starthandler = new startHandler();
    startGame.addActionListener(starthandler);

}

private class quitHandler implements ActionListener {
    public void actionPerformed(ActionEvent quitEvent) {
        System.exit(0);
    }
}

private class startHandler implements ActionListener {
    public void actionPerformed(ActionEvent startEvent) {

        guessText.getText();
        System.out.println("Hej");
    }
}

所以基本上我想知道如何存储文本文件中的单词,我应该使用哪种类型的数组以及如何将用户的一个字母输入与正确单词的一个字符进行比较。

4

2 回答 2

1

您已经在使用的 ArrayList 可能是从文本文件中存储字符串的正确方法。并不是说性能是程序最重要的部分,而是随机选择数组索引这一事实意味着 ArrayList 是一个很好的匹配,因为它的查找是即时的(与需要迭代列表的 LinkedList 相反)。

要逐个字母比较,您将需要使用子字符串(和等于)或 charAt。例如:

String hiddenWord = "foo";
char guessedLetter = 'f';
for(int i = 0; i < foo.length(); i++) {
  if(hiddenWord.charAt(i) == guessedLetter) {
    System.out.println("Matched character: " + i);
  }
}

或者

String hiddenWord = "foo";
String guessedLetter = "f";
for(int i = 0; i < foo.length(); i++) {
  if(hiddenWord.substring(i, i + guessedLetter.length()).equals(guessedLetter)) {
    System.out.println("Matched substring: " + i);
  }
}

子字符串最酷的地方在于,如果您想匹配多个字母,那么您可以使用相同的代码。因此,您可以在“foofooffo”(3 个实例)中找到“fo”的所有实例。

您应该注意用于比较的String用途和用途。这是因为 char 是一种原始类型,您正在直接比较字符的字节码值是否相等。字符串是对象,它们的“值”实际上是它们在内存中的地址。所以 "foo" == "foo" 会返回 false,因为这两个字符串是不同的对象,在内存中占据不同的地址。.equalschar==

于 2013-10-24T16:21:12.433 回答
0

看起来你进展顺利。

您目前拥有的是一个ArrayList短语(我假设文本文件中的每一行都包含一个短语)。您需要做的是标记每个短语并将生成String的 s 存储在一个新的ArrayList. 与此类似的东西:

//untested pseudoish code
ArrayList<String> hangmanWord = new ArrayList<String>();
for (String phrase : arrayWordList){
    StringTokenizer st = new StringTokenizer(phrase);
    while ( st.hasMoreElements() ){
       hangmanWord.add(st.nextElement());
    }
}

然后每次用户输入 aCharacter时,循环遍历您的hangmanWordArrayList,检查列表中的每个项目(字符串)是否包含该字符。

最后一部分的一种方法是使用该String .contains()方法(在后台实现该indexOf方法)

//more untested pseudo code 
for (String item : hangmanWord){
    if ( item.contains(guessText) ){
        //let user guess again
    }else{
        //decrement number of user tries left
        //if user has more tries let them go again
    }
 }

另外,我可能会将它们存储missedGuesses在一个 ArrayList 中,现在看起来好像您将它们String存储在一个 ArrayList 中,我认为将它们存储在一个 ArrayList 中比使用一个更容易String

于 2013-10-24T16:03:35.213 回答