Java Hangman - 用字符替换下划线

时间:2012-11-06 16:31:42

标签: java arrays char stringbuilder

所以我正在为我的java类创建一个刽子手游戏,但是我在用字母替换单词中的下划线时遇到了麻烦。我得到它打印出下划线中的单词,如:

     for(int i = 0; i < GuessWord.length(); i++) { 
                if (guesses[GuessWord.charAt(i) - 'a']) { 
                    mainword.append(words[i].charAt(i));
                }
                else {
                    mainword.append("_");

                }
                mainword.append(" ");
            }

其余的是我的其余代码。我应该提到我在Netbeans IDE 7.2中工作,我使用JLayeredPane来显示所有内容,而不是System.out.print。谢谢!

    import java.util.Random;
    import java.util.Scanner;
    import javax.swing.JOptionPane;

    public class MainFrame extends javax.swing.JFrame {

        public MainFrame() {
            initComponents();
        }

    //declare variables                      
    static String SecretWord = "";
    static String Letters = "";
    double Result = 0;
    String SetMain = null;
    StringBuilder mainword = new StringBuilder();
    StringBuilder gletters = new StringBuilder();
    boolean[] guesses = new boolean[26];
    String[] words = {"technology", "computer", "camera", "graphic design", "digital", "media", "technician", "photography", "troubleshoot", "pixels", "application", "download"};
    Random r = new Random();
    int randvalue = r.nextInt(11);
    String GuessWord = words[randvalue];


        private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
    mainword.append(SecretWord);
    //make word in underscore form
        for(int i = 0; i < GuessWord.length(); i++) { 
                if (guesses[GuessWord.charAt(i) - 'a']) { 
                    mainword.append(words[i].charAt(i));
                }
                else {
                    mainword.append("_");

                }
                mainword.append(" ");
            }

   //put in label
   SetMain = mainword.toString();
   WordLabel.setText(SetMain);
   GuessButton.setEnabled(true);
   GoButton.setEnabled(false);
}                           


private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt) {                                      
    //declare variables      
    String strGuess = GuessText.getText();
    String SetMain = null;
    String GuessedLetters = null;
    Result = 1;//(int)(Math.random() * 11) + 1;
    int errors = 0;
    int i = 0;
    char guess2 = strGuess.charAt(i);
    gletters.append(Letters);

    //*******MAJOR PROBLEM AREA FOCUS HERE*******
    do{
        //replace underscore with guessed letter
        for(i = 0; i < GuessWord.length(); i++) { 
                if (GuessWord.charAt(i) == guess2) { 
                   mainword.replace(0,i,strGuess.toUpperCase()); 
                }
                else {
                    mainword.append("_");

                }
                mainword.append(" ");
            }

    //put in labels
    SetMain = mainword.toString();
    GuessedLetters = gletters.toString();
    WordLabel.setText(SetMain);
    GuessedLabel.setText(GuessedLetters);
    GuessText.setText(null);
    GuessText.requestFocusInWindow();
    }//end of do

while(SetMain == null);
if (SetMain.equalsIgnoreCase(GuessWord)){
    //show winning message to user and reset game
    JOptionPane.showMessageDialog(null, "Congrats!");
    GuessButton.setEnabled(false);
    GoButton.setEnabled(true);
    WordLabel.setText(null);
    GuessedLabel.setText(null);
    WinsLabel.setText("1");
}
//if too many errors show lost message
else if (errors >= 5){
    JOptionPane.showMessageDialog(null, "You Lost!");
    GuessButton.setEnabled(false);
    GoButton.setEnabled(true);
    WordLabel.setText(null);
    GuessedLabel.setText(null);
    LossesLabel.setText("1");
}
    }//end of 1GAME
}                                           

任何帮助都会很棒!请不要太复杂。我还在上面的代码中标记了我的主要问题区域。

2 个答案:

答案 0 :(得分:0)

这是一种不同的方法。我们不会尝试用占位符替换未猜到的字母。在这里,我们记住了到目前为止已经猜到的所有字母(在一组中),并为每个回合重新创建了秘密字的“视图”。演示代码包含一个愚蠢的播放器,只是随机猜测字母表中的所有字母。

public static void main(final String[] args) {

    String secretWord = "fibonacci";
    Set<Character> guessedLetters = new HashSet<>();

    // (1) create some test input (all letters randomized)
    List<Character> chars = new ArrayList<>();
    for (char c = 'a'; c <= 'z'; c++) {
        chars.add(c);
    }
    Collections.shuffle(chars);

    // (2) Let's guess
    for (char guessedLetter : chars) {
        // (3) memorize all letters that have been guessed
        guessedLetters.add(guessedLetter);

        // (4) print the display version of the secret word
        boolean guessedCompletely = true;
        System.out.print("My guess: [" + guessedLetter + "] -> ");
        for (char letterOfSecretWord : secretWord.toCharArray()) {
            if (guessedLetters.contains(letterOfSecretWord)) {
                // (4a) - we already guessed this letter
                System.out.print(letterOfSecretWord);
            } else {
                // (4b) - we haven't guessed it so far
                guessedCompletely = false;
                System.out.print('_');
            }
        }
        System.out.println();
        // (5) check, if the game is won
        if (guessedCompletely) {
            System.out.println("Yeah!");
            break;
        }
    }
}

答案 1 :(得分:0)

我会尝试一种更简单的方法,您可以在其中保存一组字符,您可以根据输入进行更改。这是对这个想法的全面描述:

char guess[] = {'_', '_', '_', '_', '_', ' ', '_', '_', '_', '_', '_'};
// It's "Hello World" :)
if(input == answer.getCharAt(inputIndex))
    guess[inputIndex] = answer.getCharAt(inputIndex); 
    //replace the underscore with the correct character
else
    //Add it to a list of used characters, ignore it or do as you've been asked to    

在您的情况下,通过调用guess来创建此answer.toCharArray()数组,其中answer是具有正确单词的字符串。您将要使用replaceAll("[A-Za-z0-9]", "_")将下划线中的所有字符替换为下划线(只记得保留原始答案)。第一个参数是一个正则表达式,意思是“从A到Z的所有字符组,从a到z以及从0到9”,你需要检查一些Regular Expressions以适应它们,相信我,你会比以后更早地使用它们。

然后,您只需要在每次正确完成猜测时将guess[i]替换为answer.getCharAt(i),避免了逐字符构建字符串的繁琐工作。

这是对不同方法的简要描述,因为这是一个可以决定是否要尝试的分配,并且一般实现取决于您。我只想描述一个想法。