gpt4 book ai didi

JavaScript:在输入前一个数组中的所有单词后显示单词的下一个索引

转载 作者:行者123 更新时间:2023-12-03 06:45:14 27 4
gpt4 key购买 nike

我正在制作一个游戏,其中一系列单词从页面顶部到页面底部以动画形式呈现,用户必须在到达底部之前输入所有单词。在输入一组单词中的所有单词后,我一直在更改单词组。这是我的代码。

JS:

var word = ""; // what the user types
var targets = [["hey", "sup", "nothing", "memories", "man"], ["next", "level"]]; // array of words
var wordTyped = document.getElementById("wordtyped"); // div where it shows what the user typed
var wordlist = document.getElementById("wordlist"); // div where the array of words are displayed
var arrindex = 0;

// display the words in a div called indword. erase the current wordlist, update it with the new wordlist.
function displayWords(arr) {
wordlist.innerHTML = "";
for(var i=0; i < arr.length; i++) {
wordlist.innerHTML += "<div class='indword'>"+arr[i]+"</div>";
wordlist.innerHTML += " ";
}
}


// this is the game loop
function gameloop(arrindex) {

displayWords(targets[arrindex]); // initially display all the words in the array

// listen for typing events
document.body.addEventListener('keypress', function(e) {

word += String.fromCharCode(e.keyCode); // this is what the user types
wordTyped.innerHTML = word; // show what the user is typing on the div
console.log(word);

// this whole thing is to check if the word that the user typed is in the array targets
var index = targets[arrindex].indexOf(word);

if (index > -1) {
console.log("success");

targets[arrindex].splice(index, 1); // if what the user types exists in targets, delete that from the array

displayWords(targets[arrindex]); // then remove the existing array and display the new array.
word = ""; // reset user input
wordTyped.innerHTML = word;
}

});
}

gameloop(arrindex);

HTML:

<div class="container">
<div id="wordlist" class="godown"></div>
</div>

这就是全部内容。 http://codepen.io/davegumba/pen/OXMKOj

我尝试将游戏循环包装在这样的闭包中:

for(var i=0; i < targets.length; i++) {
(function gameloop(arrindex) {...
})(i);
}

但它直接转到数组的最后一个索引,并且它还会复制我输入的所有字母,因此输入单词“next”将输出“nneexxtt”。我该如何解决这个问题?

最佳答案

您可以通过几种方式做到这一点。

使用指针,然后在完成一部分时更新指针。

var pointer = 0;
//when work is matched, remove it from the array, and when that array is empty, increment the pointer
if(arr[pointer].length == 0){
pointer++;
}

或者你使用像 array.shift() 这样的数组函数;它在删除数组时返回数组的第一个元素。因此,每当您的工作数组为空时,请转到下一个。

var targets = [["one", "two", "three"], ["four","five","six"]];
var arr = targets.shift(); //now ["one", "two", "three"];

//when matched a word in the list.. trigger this function
function matchedWord(typedWord){
arr.splice(arr.indexOf(typedWord),1);

if(arr.length == 0){
if(targets.length>0)
arr = targets.shift(); //now ["four", "five", "six"]
} else {
//you win
}
}
}

我希望这就是您正在寻找的内容。

关于JavaScript:在输入前一个数组中的所有单词后显示单词的下一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com