我有一个小项目,工作原理如下:
- 生成一个来自数据库的随机单词
- 检查单词 中的每个字母
- 如果所有字母都正确,生成另一个随机单词并重复游戏。就像猜字游戏。
所以,问题是当我要生成第二个单词时,它以某种方式结合了第一个单词。例如,假设第一个单词是fizz
。游戏开始并猜出所有的字母。第二个字生成为buzz
。我看到第二个单词生成得很好。但当我试着猜字母的时候,不知怎么的,它也会检查第一个单词。它被看作是fibuzz
。我的目标是每次猜出所有字母后生成一个新的随机单词。
我的API:
class API{
static baseURL = "api-url"
static generateRandomWord() {
var len = 0
var rndIndex = 1;
fetch(API.baseURL)
.then(response => response.json())
.then(words => {
len = words.length;
rndIndex = this.getRandomIndex(len);
console.log(words[rndIndex]);
});
}
}
我将其称为API.generateRandomWord()
以生成一个新的随机单词。作为按钮的所有字母的事件:
button.addEventListener("click", (e) => {
e.target.disabled = true
let value = e.target.value
// letter guess logic here
})
事件按预期工作。问题是,对于第一个初始随机单词,它工作得很好,但是当我们移动到第二个单词时,第一个和第二个单词是混合的。
我所做的是添加一些逻辑按钮事件,如如果有一个词之前,删除它。我还尝试删除保存随机单词的div。到目前为止,这些都没有帮助。如有任何帮助,不胜感激。
编辑:我处理API的方式如下:基本上是将生成的随机单词传递给Word
类构造函数。
.....
.then(words => {
len = words.length
rndIndex = this.getRandomIndex(len);
console.log(words[rndIndex]);
new Word(words[rndIndex])
});
然后这个Word类开始游戏。
class Word{
static all = []
constructor(wordObject){
this.name = wordObject.name
this.id = wordObject.id
this.category = wordObject.category
Word.all.push(this); // this is the array I store the word each time
this.space = this.renderSpace(); // this is the starting point.
}
.... // other functions and logic
}
<Maybe"原因是您的Word
类在其静态属性all
中缓存所有单词。您的事件实际上无法删除任何先前的单词,因为您的删除逻辑不正确。因此,它最终会检查"所有生成的单词"的字母,而不是"只有"的字母。当前随机单词>
可能有两种解决方案:
- 检查事件中的删除逻辑,以确保它正在改变
all
并删除前一个单词。你可以尝试使用
Word.all.shift();
但我非常怀疑你会错过这个。这就引出了我的下一个观点
- 调整代码的设计方式,以避免奇怪的副作用:
要每次生成一个新的随机单词,并且只在事件中访问该新单词,如果您的static
属性是一个对象,而不是一个数组,则会更好。所以,你会有:
class Word {
static currentWord = {}
constructor(wordObject){
Word.currentWord = wordObject;
}
}
现在每次生成一个新单词时,Word.currentWord
被重置为这个新单词。你不必再担心删除事件中的前一个单词
现在你的事件看起来像这样:
button.addEventListener("click", (e) => {
e.target.disabled = true
let value = e.target.value
console.log(Word.currentWord); // accessing current Random Word
// letter guess logic here
})