尝试用JS创建一个内存游戏



const CELLS = document.getElementsByClassName("cell"); /// Getting the cells from the HTML
let counter = -1; /// Counter so I can go over each level.
let level = [
[],
[],
[],
[]
]; /// There are 4 empty levels in the array which are going to be filled eventually with random numbers representing the index of the cells

function generateLvl(n) /// filling the level with n number of index values
{
counter++;
for (let i = 0; i < n; i++) {
level[counter].push(Math.ceil(Math.random() * (n - 0) + 0));
}
}
function showCell(index) /// receives the index and highlights the cell for few milliseconds 
{
CELLS[index].classList.add("active");
setTimeout(() => {
CELLS[index].classList.remove("active");
}, 750);
}
function showLevel() /// shows the level
{
for (let i = 0; i < level[counter].length; i++) {
showCell(level[counter][i]); /// calls showCell function and sends values of the current level to highlight its cells
}
}
generateLvl(3);
showLevel();
.game-box {
display: flex;
justify-content: center;
}
.game-table {
display: grid;
grid-template-columns: 200px 200px 200px;
}
.cell {
width: 200px;
height: 200px;
border: 1px solid black;
}
.active {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/style.css">
<title>Memory Game</title>
</head>
<body>
<div class="game-box">
<div class="game-table">
<div class="cell cell-1"></div>
<div class="cell cell-2"></div>
<div class="cell cell-3"></div>
<div class="cell cell-4"></div>
<div class="cell cell-5"></div>
<div class="cell cell-6"></div>
<div class="cell cell-7"></div>
<div class="cell cell-8"></div>
<div class="cell cell-9"></div>
</div>
</div>
<script src="./js/game.js"></script>
</body>
</html>

我正在尝试创建一个游戏,玩家应该点击框并在电脑后重复顺序。有9个单元格,一旦游戏开始,玩家就会按照他应该重复的顺序看到突出显示的单元格。问题是,在我的代码中,所有单元格都会同时高亮显示,而它们应该在间隔几秒钟的时间内单独高亮显示。我该怎么解决这个问题?

问题是您的setTimeout...代码没有等待,它以异步方式工作。

我的方法是将showCell函数封装到Promise中。

async function showCell(index) {
const promise = new Promise(resolve => {
CELLS[index].classList.add("active");
setTimeout(() => {
CELLS[index].classList.remove("active");
resolve();
}, 750);
});
return promise;
}

然后你必须在for循环的每一步都等待这个承诺:

async function showLevel() /// shows the level
{
for (let i = 0; i < level[counter].length; i++) {
await showCell(level[counter][i]);
//^^^^^ await here is important
}
}

最新更新