Hangman check if String is contained in the word a

2019-09-16 13:20发布

问题:

I create a hangman game in java. I have no clue how to check and replace it. Everything works, the String word is correct and the gameboard is fine. So the game board give me the length of word as "_ _ _ _ _", for example.

Simply my Question is how I can I get the position of String word checked by the userinput and go to battleboard and change the "underline(_)" with the word wich find in the position.

public void gameStart(int topic) {
    String[] wordList = this.wordList.chooseTopicArray(topic);
    String word = this.wordList.pickRandom(wordList);
    String gameboard = spielbrettvorbereiten(word);
    Scanner userInput = new Scanner(System.in);

    for (int i = 0; i <= 16;) {

    System.out.println(gameboard);
    System.out.print("Write a letter ");

    String input = userInput.next();
    int length = input.length();
    boolean isTrue = letters.errateWortEingabe(length);

    if (isTrue == true) {
    if (word.contains(input)) {

    }


    } else {
       i = i - 1;
    }


    i++;
    }

I hope you guys can help me I am struggeling so hard.

Best Regards MichaelDev

回答1:

There are several ways to implement hangman. I will show you an approach that is easy to understand, no focus on efficiency.

You need to know the final word and remember all characters that the user has guessed:

final String word = ... // the random word
final Set<Character> correctChars = new HashSet<>();
final Set<Character> incorrectChars = new HashSet<>();

Now if a user guesses a character you should update the data-structures:

final char userGuess = ... // input from the user
if (correctChars.contains(userGuess) || incorrectChars.contains(userGuess) {
    System.out.println("You guessed that already!");
} else if (word.contains(userGuess)) {
    correctChars.add(userGuess);
    System.out.println("Correct!");
} else {
    incorrectChars.add(userGuess);
    System.out.println("Incorrect!");
}

And last you need something that prints the word as _ _ _ _ and so on. We do so by replacing all characters that are not contained in correctChars:

String replacePattern = "(?i)[^";
for (Character correctChar : correctChars) {
    replacePattern += correctChar;
}
replacePattern += "]";

final String wordToDisplay = word.replaceAll(replacePattern, "_");
System.out.println("Progress: " + wordToDisplay);

The replacePattern may then look like (?i)[^aekqw]. The (?i) matches case insensitive, the [...] is a group of symbols to match and the ^ negates the group. So all characters that are not contained inside the [...] get replaced.

And a small check if the game has finished:

if (wordToDisplay.equals(word)) {
    System.out.println("You won!");
} else if (incorrectChars.size() > 10) {
    System.out.println("You guessed wrong 10 times, you lost!");
} else {
    ... // Next round starts
}