-3

所以我正在为我的 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
}                                           

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

4

2 回答 2

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()whereanswer是具有正确单词的字符串来创建此数组。您需要使用下划线替换该字符串中的所有字符replaceAll("[A-Za-z0-9]", "_")(请记住也要保留原始答案)。第一个参数是一个正则表达式,意思是“从 A 到 Z、从 a 到 z 和从 0 到 9 的所有字符组”,你需要检查一些正则表达式来习惯它们,相信我,您迟早会使用它们。

然后,您只需在每次正确完成猜测时替换guess[i]answer.getCharAt(i),避免逐个字符构建字符串的繁琐工作,这可能很棘手。

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

于 2012-11-06T17:39:05.297 回答
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;
        }
    }
}
于 2012-11-06T17:12:15.700 回答