随机数字消消乐游戏JavaScript
时间: 2023-08-14 12:06:34 浏览: 47
好的,我可以为您提供一个简单的随机数字消消乐游戏的 JavaScript 实现。以下是代码示例:
```javascript
// 设置游戏区域的行数和列数
const ROWS = 6;
const COLS = 6;
// 设置每个方格的宽度和高度
const CELL_SIZE = 50;
// 获取游戏区域的 DOM 元素
const gameBoard = document.getElementById('game-board');
// 创建一个二维数组来表示游戏区域中的方格
let grid = new Array(ROWS);
for (let i = 0; i < ROWS; i++) {
grid[i] = new Array(COLS);
}
// 创建游戏区域中的所有方格,并将它们添加到 DOM 中
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
let cell = document.createElement('div');
cell.classList.add('cell');
cell.style.width = CELL_SIZE + 'px';
cell.style.height = CELL_SIZE + 'px';
cell.style.top = i * CELL_SIZE + 'px';
cell.style.left = j * CELL_SIZE + 'px';
gameBoard.appendChild(cell);
// 生成一个随机数字,并将它赋值给当前方格
let number = Math.floor(Math.random() * 10);
cell.innerText = number;
// 将当前方格添加到 grid 数组中
grid[i][j] = cell;
}
}
// 给每个方格添加点击事件
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
grid[i][j].addEventListener('click', function() {
// 点击方格时,检查它周围的方格是否与它的数字相同
let number = parseInt(grid[i][j].innerText);
let matchedCells = [];
if (i > 0 && parseInt(grid[i - 1][j].innerText) === number) {
matchedCells.push(grid[i - 1][j]);
}
if (i < ROWS - 1 && parseInt(grid[i + 1][j].innerText) === number) {
matchedCells.push(grid[i + 1][j]);
}
if (j > 0 && parseInt(grid[i][j - 1].innerText) === number) {
matchedCells.push(grid[i][j - 1]);
}
if (j < COLS - 1 && parseInt(grid[i][j + 1].innerText) === number) {
matchedCells.push(grid[i][j + 1]);
}
// 如果周围有与当前方格数字相同的方格,则将它们的数字设置为 0,并将当前方格的数字也设置为 0
if (matchedCells.length > 0) {
grid[i][j].innerText = '0';
matchedCells.forEach(function(cell) {
cell.innerText = '0';
});
}
});
}
}
```
这段代码会生成一个 6 行 6 列的游戏区域,每个方格中都会生成一个随机数字。当用户点击某个方格时,代码会检查它周围的方格是否与它的数字相同,如果有的话,就将它们的数字设置为 0。用户可以不断点击方格,直到游戏结束为止。注意,这只是一个简单的实现,实际的游戏可能还需要考虑其他因素,比如计分、游戏结束条件等等。