我用 Java 创建了一个刽子手游戏。我不知道如何检查和更换它。一切正常,字符串字正确,游戏板也很好。因此,游戏板给我的单词长度为“_ _ _ _ _”,例如。
我的问题就是如何获取用户输入检查的字符串单词的位置,然后转到战斗板并用在该位置找到的单词更改“下划线(_)”。
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++;
}
希望大家能帮助我,我很努力。
致以诚挚的问候
最佳答案
有多种方法可以实现hangman。我将向您展示一种易于理解的方法,不注重效率。
您需要知道最终的单词并记住用户猜到的所有字符:
final String word = ... // the random word
final Set<Character> correctChars = new HashSet<>();
final Set<Character> incorrectChars = new HashSet<>();
现在,如果用户猜测一个字符,您应该更新数据结构:
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!");
}
最后,您需要将单词打印为 _ _ _ _
等。我们通过替换 CorrectChars
中未包含的所有字符来做到这一点:
String replacePattern = "(?i)[^";
for (Character correctChar : correctChars) {
replacePattern += correctChar;
}
replacePattern += "]";
final String wordToDisplay = word.replaceAll(replacePattern, "_");
System.out.println("Progress: " + wordToDisplay);
replacePattern
可能看起来像 (?i)[^aekqw]
。 (?i)
匹配不区分大小写,[...]
是一组要匹配的符号,^
否定该组。因此,所有未包含在 [...]
内的字符都会被替换。
并检查游戏是否已完成:
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
}
关于java - Hangman 检查单词中是否包含字符串并替换它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44812465/