在我的游戏中,当点击“下一个问题”按钮时,它应该在网格中选择一个新单词供用户拼写。它做到了这一点,但问题在于,有时随机化会将其带回已经存在的单词,而不是去另一个单词。我需要做到这一点,以便它选择其他任何一个。
//Next question click event
$('.next-question').on('click', function () {
$('td').removeClass('highlight-problem');
var r = rndWord;
while (r == rndWord) {
rndWord = Math.floor(Math.random() * (listOfWords.length));
}
//Adds and removes nesesary classes
$('td[data-word="' + listOfWords[rndWord].name + '"]').addClass('highlight-problem');
$('td[data-word=' + word + ']').removeClass('wrong-letter').removeClass('wrong-word').removeClass('right-letter');
var spellSpace = $('td[data-word="' + listOfWords[rndWord].name + '"]').hasClass('right-word');
if (spellSpace) {
$(".next-question").eq(($(".next-question").index($(this)) + 1) %$(".next-question").length).trigger("click");
} else {
$("#hintSound").attr('src', listOfWords[rndWord].audio);
hintSound.play();
$("#hintPic").attr('src', listOfWords[rndWord].pic);
$('#hintPicTitle').attr('title', listOfWords[rndWord].hint);
}
});
答案 0 :(得分:3)
在你的while循环之前rndWord
的价值是多少?它看起来像一个范围问题 - 您需要在函数外部声明rndWord
,以便在调用之间保留它或者每次都传递它。
var rndWord;
function() {
//Next question click event
....
var r = rndWord;
while (r == rndWord) {
rndWord = Math.floor(Math.random() * (listOfWords.length));
}
进一步澄清后:
var currentWord;
function ClickEventHere() {
r = currentWord;
while (r == currentWord) {
nextIndex = Math.floor(Math.random() * (listOfWords.length));
currentWord = listOfWords[nextIndex];
}
...
}
将你的while语句中的整数r
与数组进行比较是没有意义的 - 你可以将索引或单词本身存储在全局中,然后检查以确保它不存在重复使用。
在此循环之后,currentWord
将包含下一个不同的单词
答案 1 :(得分:0)
查找随机单词,与上次找到的单词相同,如果找到另一个单词。只要你有足够数量的单词就足够了。