JavaScript 数字消消乐源代码
时间: 2023-10-10 13:11:38 浏览: 197
消消乐源码
以下是一个简单的 JavaScript 数字消消乐游戏的源代码示例:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>数字消消乐游戏</title>
</head>
<body>
<h1>数字消消乐游戏</h1>
<div id="game-board"></div>
<button onclick="newGame()">开始游戏</button>
</body>
</html>
```
JavaScript 代码:
```javascript
// 定义游戏区域的行数和列数
const ROWS = 5;
const COLS = 5;
// 随机生成一个指定范围内的整数
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// 创建一个新的游戏面板
function createGameBoard() {
let board = [];
for (let i = 0; i < ROWS; i++) {
let row = [];
for (let j = 0; j < COLS; j++) {
// 随机生成 1~9 的整数
row.push(randomInt(1, 9));
}
board.push(row);
}
return board;
}
// 更新游戏面板的显示
function updateGameBoard(gameBoard) {
let boardDiv = document.getElementById("game-board");
boardDiv.innerHTML = "";
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
let cell = document.createElement("div");
cell.className = "cell";
cell.innerHTML = gameBoard[i][j];
boardDiv.appendChild(cell);
}
}
}
// 消除相邻的数
function removeAdjacentNumbers(gameBoard) {
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
let curr = gameBoard[i][j];
if (i > 0 && gameBoard[i - 1][j] === curr) {
gameBoard[i - 1][j] = 0;
}
if (i < ROWS - 1 && gameBoard[i + 1][j] === curr) {
gameBoard[i + 1][j] = 0;
}
if (j > 0 && gameBoard[i][j - 1] === curr) {
gameBoard[i][j - 1] = 0;
}
if (j < COLS - 1 && gameBoard[i][j + 1] === curr) {
gameBoard[i][j + 1] = 0;
}
}
}
}
// 移除已经标记为 0 的数
function removeMarkedNumbers(gameBoard) {
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
if (gameBoard[i][j] === 0) {
gameBoard[i][j] = randomInt(1, 9);
}
}
}
}
// 开始新游戏
function newGame() {
let gameBoard = createGameBoard();
updateGameBoard(gameBoard);
// 每隔 1 秒钟执行一次消除相邻的数和移除已经标记为 0 的数的操作
setInterval(() => {
removeAdjacentNumbers(gameBoard);
removeMarkedNumbers(gameBoard);
updateGameBoard(gameBoard);
}, 1000);
}
```
CSS 代码:
```css
.cell {
width: 50px;
height: 50px;
border: 1px solid black;
display: inline-block;
text-align: center;
font-size: 30px;
line-height: 50px;
margin-right: -5px;
margin-bottom: -5px;
}
```
阅读全文