- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习 Java,在此过程中我正在编写一个猜词游戏。现在我的问题如下:
假设要猜测的单词是“lingo”。并假设“oodle”是您建议的词。在处理您的猜测时,应输出以下内容:正确字母: 无错误位置字母:“o”在第一个位置,“l”在第四个位置请注意,第二个“o”不应被视为错误位置的字母,因为我们之前已经报告过一个“o”。因此,如果您输入“ooooo”,则仅应突出显示最后一个字母,因为它位于正确的位置;如果您输入“ooooz”,则仅应突出显示第一个字母,而不是其他“o”。
我尝试了一些解决方案,但似乎都失败了。我知道有一种聪明/不太复杂的方法可以做到这一点。那么有人可以帮我吗?
代码:
// / Indicates whether a letter has been accounted for
// / while highlighting letters in the guess that are not
// / in the correct position
private Boolean[][] marked = new Boolean[WordLength][5];
// / Holds which all letters have been solved so far
private Boolean[][] solved = new Boolean[WordLength][6];
public void CheckLetters() {
for (int j = 0; j < currentAttempt; j++) {
tempWord = list.get(j); //The guessed words
for (int i = 0; i < WordLength; i++) {
if (tempWord.charAt(i) == CurrentPuzzleWord.charAt(i)) {
solved[i][j] = true; //CurrentPuzzleWord is the string with the hidden word
} else if (CurrentPuzzleWord.indexOf(tempWord.charAt(i)) != -1) {
marked[i][j] = true;
}
}
}
最佳答案
因此您需要进行多次检查。
String oracle = "lingo";
String input = "oodle";
String modOracle = "";
// ArrayList for noting the matched elements
ArrayList<Integer> match = new ArrayList<Integer>();
// ArrayList for the correct letters with wrong position
ArrayList<Integer> close = new ArrayList<Integer>();
// Length of the Strings of interest
int length = oracle.length;
显然,您要检查的第一件事是匹配且位置正确的字母。因此,取出 oracle 字符串和用户输入的字符串,逐个字符进行比较,注意哪些是正确的。
// may need to check that oracle and input are same length if this isn't enforced.
for (int i = 0; i < length; i++) {
if (input.substring(i,i+1).equals(oracle.substring(i,i+1))) {
// there is a match of letter and position
match.add(i);
}
else
modOracle = modOracle + oracle.substring(i,i+1);
}
然后,您需要再次检查字母是否正确但位置错误。为此,首先从上次检查中取出正确的字母。然后,对于输入字符串中与 oracle 字符串中的字母匹配的每个字母,记下匹配并将其从检查的其余部分中删除。继续此操作,直到检查完整个输入字符串。
for (int i = 0; i < length; i++) {
if (match.contains(i))
continue;
// String to match
String toMatch = input.substring(i,i+1);
for (int j = 0; j < modOracle.length; j++) {
if (toMatch.equals(modOracle.substring(j,j+1))) {
close.add(i);
// then remove this letter from modOracle
// need small utility method for this.
break;
}
}
}
合并两次检查的结果并将其输出给用户。
我不确定您希望如何向用户显示结果,但您现在拥有与 oracle/input 中完全正确的位置相对应的 arraylist match
和 arraylist close
对应于 oracle/input 中的位置,使得字母出现在某处,但不在该位置。
关于java - 字母位置,找出猜词游戏的聪明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689385/
我正在用 python 编写一个猜词游戏。这是我的学校项目。我快完成了,我只是有一件事有问题。我不知道如何掩盖一个词。例如,如果单词是 monkey,程序应该显示 ------ 并且当用户猜一个字母时
我是一名优秀的程序员,十分优秀!