【发布时间】:2020-06-20 17:24:25
【问题描述】:
我正在观看有关使用 Vanilla JavaScript、HTML 和 CSS 编写 2048 游戏的 YouTube 教程。在看教程的时候,我想我也可以重构讲师给出的代码。在某一时刻,她调用了两次函数以在网格的随机位置生成两个编号的正方形(不是 0)。我想我可以编写一个函数(称为 randomSquaresGenerator),给定所需的不同位置数量可以生成相应数量的随机编号正方形。事情是,经过一些测试(在我的浏览器上刷新),有时我看到的方块少于所需的方块。我发现这是因为在某些调用中,该函数可能会检查一个已经编号的正方形并通过。我仍然没有想出如何解决这个问题。有什么想法吗?
这是我的 JavaScript 代码:
document.addEventListener("DOMContentLoaded", () => {
const gridDisplay = document.querySelector(".grid");
const scoreDisplay = document.querySelector(".score");
const resultDisplay = document.querySelector(".result");
const width = 4;
const squaredWidth = width ** 2;
let squares = [];
function createBoard(width) {
for (let i = 0; i < squaredWidth; i++) {
square = document.createElement("div");
square.innerHTML = 0;
gridDisplay.appendChild(square);
squares.push(square);
}
}
//The function with the unwanted behavior.
function randomSquaresGenerator(positions) {
for (let i = 0; i < positions; i++) {
let randomSquare = Math.floor(Math.random() * squaredWidth);
if (squares[randomSquare].innerHTML == 0) {
squares[randomSquare].innerHTML = 2;
}
}
}
createBoard();
randomSquaresGenerator(2);
});
还有我的 HTML 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>2048</title>
<link rel="stylesheet" href="style.css" />
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div class="score-container">
<div class="score-title">SCORE</div>
<span class="score">1000</span>
</div>
<div class="grid"></div>
<div class="result"></div>
</body>
</html>
【问题讨论】:
-
不要使用固定轮数的
for(...)。使用while并计算“生成”了多少个正方形。如果数字等于positions,则退出循环。 -
非常感谢!这确实有效,现在适用于任何给定的
positions值。 -
将您的解决方案添加为答案并接受它(或删除问题),以便将其标记为“问题已解决”
标签: javascript function loops frontend