刽子手掩盖字符串,取消隐藏角色

时间:2012-08-30 20:46:51

标签: java

请大家和我一起出去,我发布了很多问题,人们继续投票来关闭这个问题,所以我希望这个问题有所不同。我正在忙着编写一个刽子手应用程序,并且我正在编写代码以隐藏字符串中的每个字符(这个词被猜到)并带有“ - ”......我发布了很多内容关于锄头的问题和我的一个回复是:Hangman - hide String and then unhide each char if guessed correct

public class HangmanWord {

private static final char HIDECHAR = '_';

private String original;     
private String hidden;  

public HangmanWord(String original) {
    this.original = original;
    this.hidden = this.createHidden();
}

private String createHidden() {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < this.original.length; i++) {
        sb.append(HIDECHAR);
    }
    return sb.toString();
}

public boolean check(char input) {
    boolean found = false;
    for (int i = 0; i < this.original.length; i++) {
        if (this.original[i].equals(input)) {
            found = true;
            this.hidden[i] = this.original[i];
        }
    }
    return found;
}

//getter and setter
}

public class TestClass() {

public static void main(String[] args) {
    String secret = "stackoverflow";
    int wrongGuesses = 0;
    HangmanWord hngm = new HangmanWord(secret);
    System.out.println(hngm.getHidden()); // _____________
    if (hngm.check('a')) {
        System.out.println(hngm.getHidden()); // __a_________
    }
    else {
       wrongGuesses++;
    }
    //... and so on...
}
}

我尝试将此代码与我一起使用,但我遇到了很多错误和结论,但是我的代码无效。在我的代码中,我创建了一个数组按钮,如果用户点击按钮,我会收到一条消息,说明该字母是否在单词中......现在我想将这些代码替换为不给我的地方消息但取消隐藏字符,如果没有字符则必须更改图像

如果有可能,任何人都可以解释为什么它不适用于我的代码,或者任何人都可以向我解释该怎么做...

我的按钮数组:

public JButton getButton(final String text){
   final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
             if(original.toUpperCase().indexOf(button.getText())!=-1){
                 JOptionPane.showMessageDialog(null, "Your word does contain " + text       );
             }
             else{
                 JOptionPane.showMessageDialog(null, "There is no " + text );
                 error++;
                    if(error >= 0) imageName = "hangman1.jpg";
                    if(error >= 1) imageName = "hangman2.jpg";
                    if(error >= 2) imageName = "hangman3.jpg";
                    if(error >= 3) imageName = "hangman4.jpg";
                    if(error >= 4) imageName = "hangman5.jpg";
                    if(error >= 5) imageName = "hangman6.jpg";
                    if(error >= 7) imageName = "hangman7.jpg"; 
             }
             }
             });
             return button;
}

我的完整代码:

import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;

public final class Hangman extends JFrame implements ActionListener{
String original = readWord();
int error;
String imageName;

JButton btnAddWord = new JButton("Add New Word");
JButton btnRestart = new JButton("Restart");
JButton btnHelp = new JButton("Help");
JButton btnExit = new JButton("Exit");

JLabel word = new JLabel(original);

static JPanel panel1 = new JPanel();
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JPanel panel4 = new JPanel();

public Hangman(){
    Container content =getContentPane();
    content.setLayout(new GridLayout(0,1));

   btnAddWord.addActionListener(this);
   btnRestart.addActionListener(this);
   btnHelp.addActionListener(this);
   btnExit.addActionListener(this);

   ImageIcon icon = null;
   if(imageName != null){
   icon = new ImageIcon(imageName);
                    }
  JLabel image = new JLabel();
  image.setIcon(icon);
  panel2.add(image);

   panel3.add(word);
   panel4.add(btnAddWord);
   panel4.add(btnRestart);
   panel4.add(btnHelp);
   panel4.add(btnExit);

    for(char i = 'A'; i <= 'Z'; i++){
        String buttonText = new Character(i).toString();
        JButton button = getButton(buttonText);
        panel1.add(button);
    }
}

public JButton getButton(final String text){
   final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
             if(original.toUpperCase().indexOf(button.getText())!=-1){
                 JOptionPane.showMessageDialog(null, "Your word does contain " + text     );
             }
             else{
                 JOptionPane.showMessageDialog(null, "There is no " + text );
                 error++;
                    if(error >= 0) imageName = "hangman1.jpg";
                    if(error >= 1) imageName = "hangman2.jpg";
                    if(error >= 2) imageName = "hangman3.jpg";
                    if(error >= 3) imageName = "hangman4.jpg";
                    if(error >= 4) imageName = "hangman5.jpg";
                    if(error >= 5) imageName = "hangman6.jpg";
                    if(error >= 7) imageName = "hangman7.jpg"; 
             }
             }
             });
             return button;
}
public String readWord(){
    try{
        BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
        String line = reader.readLine();
        List<String> words = new ArrayList<String>();
        while(line != null){
            String[] wordsLine = line.split(" ");
            boolean addAll = words.addAll(Arrays.asList(wordsLine));
            line = reader.readLine();
        }
        Random rand = new Random(System.currentTimeMillis());
        String randomWord = words.get(rand.nextInt(words.size()));
        return randomWord;

}catch (Exception e){
    return null;
}
}
public void actionPerformed(ActionEvent e){
    if(e.getSource() == btnAddWord){
        try{
            FileWriter fw = new FileWriter("Words.txt", true);
            PrintWriter pw = new PrintWriter(fw, true);

            String word = JOptionPane.showInputDialog("Please enter a word: ");

            pw.println(word);
            pw.close();
        }
        catch(IOException ie){
            System.out.println("Error Thrown" + ie.getMessage());
        }
    }
    if(e.getSource() == btnRestart){

    }
    if(e.getSource() == btnHelp){
        String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
               + "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
               + "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
               + "\n"
               + "\nThe game is over when:"
               + "\nThe guessing player completes the word, or guesses the whole word correctly"
               + "\nThe other player completes the diagram";
       JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
    }
    if(e.getSource() == btnExit){
        System.exit(0);
    }
}

public static void main (String [] args){
    Hangman frame = new Hangman();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 600);
    frame.add(panel1, BorderLayout.NORTH);
    frame.add(panel2, BorderLayout.CENTER);
    frame.add(panel3, BorderLayout.SOUTH);
    frame.add(panel4, BorderLayout.SOUTH);
}
}

2 个答案:

答案 0 :(得分:1)

您的代码已经有了一个良好的开端,但首先您需要清楚地了解设计,之前编写代码。让我们一步一步地考虑一下:

  • 启动应用程序时,您将加载文件中的所有单词。所以这是一个只执行一次的步骤,应保存其结果(文件中的单词)。
  • 上一步似乎与您的GUI代码无关,因此您可能希望在main方法中执行此操作,然后将结果传递给GUI类。您甚至可以将此功能提取到单独的类中,同时选择随机单词。
  • 显示GUI后,会显示一个标记隐藏字的标签。此标签的文本应包含与单词的字符一样多的隐藏字符('-')。
  • 每当按下正确的按钮时,应显示单词中所有匹配的字符。
  • 每当按下错误按钮时,错误计数器会递增并显示图像。
  • 当发现整个单词时,应禁用字符按钮。

这导致了一种设计,其中您有一个单独的辅助类,其中包含用于读取单词文件的方法和另一个用于选择随机单词的方法。可能是这样的:

class WordsReader {
    public String[] readWords(String filename) {
        // ...
    }

    public String chooseWord(String[] words) {
        // ...
    }
}

选择新单词后,您应该更新标签。这就是上面提到的HangmanWord类派上用场的地方。它存储原始单词及其隐藏表示。这允许您在按钮的处理程序中调用check方法,并使用更新的隐藏表示更新标签的文本。其余的代码应该可以正常工作,尽管它仍然可以改进。

答案 1 :(得分:0)

你可以得到字符串的字符,并用新字符串中的' - '替换猜到的字母,然后显示(在幕后你还有完整的字符串)

public [static] String hideString(String string, int[] guessedLetterIndices) {
    char[] chars = string.toCharArray();
    for(int index : guessedLetterIndices)
        chars[i] = '-';//Replace this with any letter
    for(int i = 0; i < chars.length; i++) {
        char c = '-';
        for(int index : guessedLetterIndices)
            if(index == i)
                c = chars[i];
        chars[i] = c;
    }

    return new String(chars);
}

或者如果你现在有一个他们选择的字符数组,而不是字符索引...

public [static] String hideString(String string, char[] guessedLetters) {
    char[] chars = string.toCharArray();
    char[] hidden = (string.replaceAll("(.|\n)", "-").toCharArray();
    for(int i=0;i<chars.length;i++) {
        for(char c : guessedLetters)
            if(chars[i] == c) {
                hidden[i] = chars[i];
                break;
            }
    ]
    return new String(chars);
}

这就是我要做的。至于为什么你的工作不起作用,你能告诉我你得到的错误吗?确保你正在导入StringBuilder和东西(他们使用的任何其他东西)