我想要做“城市消消乐”这款游戏,请给我代码
时间: 2023-11-20 16:04:46 浏览: 66
消消乐代码,可以玩会
4星 · 用户满意度95%
好的,以下是一个简单的“城市消消乐”游戏的代码示例,你可以尝试着理解并自行修改:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>城市消消乐</title>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid #ccc;
display: inline-block;
margin: 5px;
}
</style>
</head>
<body>
<h1>城市消消乐</h1>
<div id="game"></div>
<button onclick="startGame()">开始游戏</button>
<script src="game.js"></script>
</body>
</html>
```
Javascript 代码(game.js):
```javascript
const colors = ["red", "blue", "green", "yellow", "orange"];
const ROWS = 8;
const COLS = 8;
let score = 0;
let gameboard = [];
function startGame() {
score = 0;
gameboard = generateGameboard(ROWS, COLS);
renderGameboard(gameboard);
}
function generateGameboard(rows, cols) {
let board = [];
for (let i = 0; i < rows; i++) {
let row = [];
for (let j = 0; j < cols; j++) {
row.push(colors[Math.floor(Math.random() * colors.length)]);
}
board.push(row);
}
return board;
}
function renderGameboard(gameboard) {
let game = document.getElementById("game");
game.innerHTML = "";
for (let i = 0; i < gameboard.length; i++) {
let row = gameboard[i];
let divRow = document.createElement("div");
for (let j = 0; j < row.length; j++) {
let divBox = document.createElement("div");
divBox.classList.add("box");
divBox.style.backgroundColor = row[j];
divBox.dataset.row = i;
divBox.dataset.col = j;
divBox.addEventListener("click", handleClick);
divRow.appendChild(divBox);
}
game.appendChild(divRow);
}
}
function handleClick(e) {
let row = parseInt(e.target.dataset.row);
let col = parseInt(e.target.dataset.col);
let color = gameboard[row][col];
let count = removeBlocks(row, col, color);
if (count > 1) {
score += count;
updateScore(score);
renderGameboard(gameboard);
}
}
function updateScore(score) {
let h1 = document.querySelector("h1");
h1.innerText = `城市消消乐 - 得分:${score}`;
}
function removeBlocks(row, col, color) {
let count = 0;
if (gameboard[row][col] !== color) {
return count;
}
gameboard[row][col] = "";
count++;
if (row > 0) {
count += removeBlocks(row - 1, col, color);
}
if (row < ROWS - 1) {
count += removeBlocks(row + 1, col, color);
}
if (col > 0) {
count += removeBlocks(row, col - 1, color);
}
if (col < COLS - 1) {
count += removeBlocks(row, col + 1, color);
}
return count;
}
```
这个游戏的实现思路是:生成一个指定行数和列数的游戏板(即一张色块地图),然后在点击某个色块时将与之相邻的、颜色相同的色块全部消除,并计算分数。
阅读全文