创建一个随机数组来比较用户数组和simon says游戏中的闪光



我正在学校里制作一个西蒙游戏作为学生作业项目。我通过在纯js中的表中输入单元格来动态构建"纸牌游戏",现在我想让"纸牌游戏"在随机序列中闪烁,所以我创建了一个随机var,并在evryrandom中添加了一个classList,但问题是

1( 我想创建一个随机数组,在播放时在用户数组之间进行比较,似乎我无法对其进行classLiss.add()

2( 我想"闪现"纸牌游戏",每次它都会闪现一次,而不是同时闪现(而且在第一回合它会闪现一次第二回合它会闪烁两次{不在同一时间.exc}(我确实使用了setTimeout函数来删除classList

这是"卡片显示"和随机功能的代码:

function cards(user) {
userchioce = parseInt(user.value);
if (userchioce == 4) {
var table = document.getElementById("mytable");
document.getElementById("mytable").innerHTML = "";
for (var i = 0; i < 2; i++) {
var row = table.insertRow(0);
for (var j = 0; j < 2; j++) {
var cell = row.insertCell(-1);
}
}
var t = document.getElementById("mytable");
var idnum = 0;
counter = 0;
for (var r = 0; r < t.rows.length; r++) { //luop at length of rows 
for (var c = 0; c < t.rows[r].cells.length; c++) { //luop at length of rows and cells 
t.rows[r].cells[c].style.backgroundColor = colorarry[counter];
t.rows[r].cells[c].innerHTML = colorarry1[counter];
t.rows[r].cells[c].setAttribute("class", "td1");
t.rows[r].cells[c].setAttribute("id", "tdd" + idnum++);
counter++;
}
}
}
counter = 0;//end of if 4
function getrandom(rnd) {
rnd = Math.floor(Math.random() * userchioce);
var id = "tdd";
var fullid = id + rnd;
var dispaly = document.getElementById(fullid);
dispaly.classList.add("flash");
{
setTimeout(function () {
dispaly.classList.remove("flash");
}, 850);
}
}

好吧,让我们先清理一下。您正在创建循环来创建单元格,然后再次创建循环来修改它们,您应该立即修改它们。

if (userchioce == 4) {
var table = document.getElementById("mytable");
document.getElementById("mytable").innerHTML = "";
var idnum = 0;
for (var i = 0; i < 2; i++) {
var row = table.insertRow(0);
for (var j = 0; j < 2; j++) {
var cell = row.insertCell(-1);
cell.style.backgroundColor = colorarry[idnum];
cell.innerHTML = colorarry1[idnum];
cell.setAttribute("class", "td1");
cell.setAttribute("id", "tdd" + idnum++);
}
}
}

我还删除了counter变量,转而使用idnum变量。它们都在同一位置定义为0,并且以相同的速度递增。。。

不能一个接一个地显示灯光,因为只显示一次。应该有一个地方可以记录以前的随机事件。

var moves = [];
function newTurn() {
var rnd = Math.floor(Math.random() * userchioce);
// Add the new random to the moves history.
moves.push(rnd);
//create a copy, we'll be playing with it.
var movesToShow = moves.slice();
showMove();
}
function showMove(moveList){
//Remove first value of the list of moves and use it to show.
var move = moveList.shift();
var id = "tdd";
var fullid = id + move;
var display= document.getElementById(fullid);
display.classList.add("flash");
//Wait a little before removing the hightlight.
setTimeout(function () {
display.classList.remove("flash");
if(moveList.length>0){
//There are more moves, wait just a little
setTimeout(function(){
//Display a new move.
showMove(moveList);
},100);
}
}, 850);
}
// call this to start a new turn.
newTurn();

此外,我想敦促你纠正你剧本中的所有错别字。"dispaly","userchioce"这会让你很难跟上。

最新更新