所以我对javascript和一般编码很陌生。我制作 Wordle 算法只是为了提高我的编码技能。在制作这个算法时,我意识到我将不得不重新创建 Wordle。所以我在网上查找了用 java 脚本编写的 wordle 游戏,而我发现的所有游戏都发现了一个我不想拥有的缺陷。
我看到的缺陷是在 IF 语句中检查 wordle 答案中的一个字母。特别是当字母在单词中但不在正确位置时。我看到的娱乐有一个看起来像这样的 IF 语句。
IF (answerWord.includes(guessLetter[i])) {
guessLetter[i] = color.(yellow)
}
(这不是他们写它的方式,但它的主要思想)
我的主要关注点是.includes
. 这是行不通的,因为假设我们的猜测词是“同意”而答案词是“准备好”。“同意”中的 2 个 E 是黄色的,我们不希望这样,因为它们在“准备好”中只有 1 个 E。所以我们只希望“同意”中的第一个 E 是黄色的,而不是第二个 E。
所以我决定自己解决这个问题,我能够想出这个并且它有效。至少我很确定它有效,基于我测试它的许多单词。
所以我的问题是,既然我在做一个算法,我会做很多计算,这是我能写的最有效的还是我可以做得更好?
let guessWord = "agree"; // the first word thats inputed
let answerWord = "ready"; // the answer to the wordle
/*
'letterCheck' is an array that tells what condition each letter in 'startLetter' is, based on the answer word
2 = the letter is in the word and in the correct place (GREEN)
1 = the letter is in the word but not in the correct place (YELLOW)
0 = the letter in not in the word (GREY)
*/
var letterCheck = ["0", "0", "0", "0", "0"];
var guessLetter = ["A", "A", "A", "A", "A"]; // the separated letters of 'startword' in a array
var answerLetter = ["A", "A", "A", "A", "A"]; // the separated letters of 'answord' in a array
//adds the start word and the answer world to the arrays
for (var i = 0; i < 5; i++) {
guessLetter[i] = guessWord.substring(i, i + 1);
answerLetter[i] = answerWord.substring(i, i + 1);
}
console.log(guessLetter);
console.log(letterCheck);
console.log(answerLetter);
//this loops goes though every letter one by one
for (var i = 0; i < 5; i++) {
//checks if the letter is in the right spot
if (guessLetter[i] == answerLetter[i]) {
letterCheck[i] = "2";
console.log(guessLetter[i]);
console.log(letterCheck);
} else if (answerWord.includes(guessLetter[i])) {
//checks if there is more than one letter in start word or its the first letter
if (guessWord.split(guessLetter[i]).length - 1 == 1 || i == 0) {
letterCheck[i] = "1";
console.log(guessLetter[i]);
console.log(letterCheck);
//checks if the the amount of same letters in start words is equel to the amount of same letters in answer word
} else if (guessWord.split(guessLetter[i]).length - 1 == answerWord.split(guessLetter[i]).length - 1) {
letterCheck[i] = "1";
console.log(guessLetter[i]);
console.log(letterCheck);
//opposite of above
} else if (guessWord.split(guessLetter[i]).length - 1 != answerWord.split(guessLetter[i]).length - 1) {
letterCheck[i] = "1";
console.log(guessLetter[i]);
console.log(letterCheck);
// checks if any of the letters infront of it are the same as it
for (var j = 0; j < i; j++) {
if (guessLetter[i] == guessLetter[j]) {
letterCheck[i] = "0";
console.log(guessLetter[i]);
console.log(letterCheck);
}
}
}
} else {
letterCheck[i] = "0";
console.log(guessLetter[i]);
console.log(letterCheck);
}
}
console.log(guessLetter);
console.log(letterCheck);
console.log(answerLetter);
console.log
他们只是帮助我调试。)
抱歉,如果我的代码可能会令人困惑,我不是最擅长保持代码清洁的人。如果您有任何困惑或疑问,我会尽力解决任何困惑。