部分数据来源:
ChatGPT
2048游戏规则
2048是一款数字益智类游戏,玩家需要通过合并数字方块来获得更高的分数。游戏的规则非常简单,只需要使用上下左右方向键移动数字方块,当两个相同数字方块碰撞时,会合并成一个数字方块。每次移动后,系统会在空白的方格随机生成一个数字方块,数字方块的大小为2的幂(即2、4、8、16…)。当游戏棋盘上没有空白方格时,游戏结束。
2048游戏使用教程
进入游戏界面后,玩家可以使用上下左右方向键来移动数字方块。每次移动后,系统都会在空白的方格随机生成一个数字方块。
当两个相同数字方块碰撞时,会合并成一个数字方块。例如,当有两个数字为2的方块相邻时,将它们合并后就会变成一个数字为4的方块。同样地,当有两个数字为4的方块相邻时,将它们合并后就会变成一个数字为8的方块,以此类推。
当游戏棋盘上没有空白方格时,游戏结束。此时,玩家可以选择重新开始游戏或退出游戏。
编程思路步骤
下面是2048游戏的编程思路步骤:
步骤一、获取页面元素
在开发2048游戏之前,首先需要获取所有相关的页面元素,如数字方块元素、开始游戏按钮、重置按钮、分数显示元素等,并将它们存储到变量中,以便后续使用。
步骤二、初始化游戏状态
定义一个二维数组,用来存储游戏的状态,初始化分数为0。然后清空所有的方块元素,并随机生成两个数字为2的方块。最后将游戏状态和分数更新到页面上。
步骤三、监听键盘事件
使用键盘事件监听器来实现方块的移动操作。当用户按下方向键时,检查是否可以移动,并更新游戏状态和对应的DOM元素。
步骤四、定义辅助函数
定义一些辅助函数来方便代码的编写,例如生成随机数、检查游戏是否结束等。
步骤五、开始游戏
当用户点击“开始游戏”按钮时,初始化游戏,并隐藏“开始游戏”按钮、显示“重置”按钮。
步骤六、重置游戏
当用户点击“重置”按钮时,重置游戏状态并更新所有的DOM元素。
代码注释
在您提供的代码中,已经添加了一些注释,以帮助您更好地理解代码的逻辑。这些注释主要包括了以下内容:
- 初始化页面元素
- 定义变量和常量
- 初始化游戏状态
- 监听键盘事件
- 辅助函数:生成随机数、检查游戏是否结束
- 开始游戏
- 重置游戏
这些注释可以帮助您更好地理解代码的含义和作用,如果您还有其他需要了解的地方,可以在代码中添加对应的注释。
下面是代码实现:
CSS
body {
font-family: 'Microsoft YaHei', sans-serif;
text-align: center;
}
h1 {
font-size: 40px;
}
#game-board {
border: 10px solid #BBADA0;
border-radius: 5px;
display: inline-grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(4, 1fr);
width: 450px;
height: 450px;
margin: 20px auto 0;
padding: 10px;
background-color: #BBADA0;
box-shadow: 0px 0px 20px #888888;
}
.box {
font-size: 40px;
color: #776E65;
border: 5px solid #BBADA0;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
background: #CDC1B4;
box-shadow: 0px 0px 10px #888888;
}
#start-button,
#reset-button {
font-size: 20px;
padding: 10px 20px;
margin-top: 20px;
background-color: #8F7A66;
border: none;
border-radius: 5px;
color: white;
text-shadow: 1px 1px 1px #494949;
box-shadow: 2px 2px 5px #888888;
}
h2 {
font-size: 25px;
margin: 30px auto 10px;
}
#score {
color: #8F7A66;
font-weight: bold;
}
.square.selected {
border-radius: 50px;
box-shadow: 0 0 10px #1abc9c !important;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>2048小游戏</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>2048小游戏</h1>
<div id="game-board">
<!-- 生成16个盒子 -->
<!-- 第一行方块 -->
<div id="square-0-0" class="square box"></div>
<div id="square-0-1" class="square box"></div>
<div id="square-0-2" class="square box"></div>
<div id="square-0-3" class="square box"></div>
<!-- 第二行方块 -->
<div id="square-1-0" class="square box"></div>
<div id="square-1-1" class="square box"></div>
<div id="square-1-2" class="square box"></div>
<div id="square-1-3" class="square box"></div>
<!-- 第三行方块 -->
<div id="square-2-0" class="square box"></div>
<div id="square-2-1" class="square box"></div>
<div id="square-2-2" class="square box"></div>
<div id="square-2-3" class="square box"></div>
<!-- 第四行方块 -->
<div id="square-3-0" class="square box"></div>
<div id="square-3-1" class="square box"></div>
<div id="square-3-2" class="square box"></div>
<div id="square-3-3" class="square box"></div>
</div>
<button id="start-button">开始游戏</button>
<button id="reset-button" style="display:none;">重置</button>
<h2>分数:<span id="score">0</span></h2>
<script src="script.js"></script>
</body>
</html>
JS
const boxes = Array.from(document.getElementsByClassName("box")); // 获取所有方块盒子
// 创建一个二维数组代表盘面,0代表空格子
let board = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
];
const startButton = document.getElementById("start-button"); // 获取开始游戏按钮
const resetButton = document.getElementById("reset-button"); // 获取重置按钮
const scoreDisplay = document.getElementById("score"); // 获取分数显示元素
// 计算空闲格子数
function countEmpty() {
let empty = 0;
board.forEach(row => {
row.forEach(cell => {
if (cell === 0) empty++;
});
});
return empty;
}
// 在空闲位置随机出现一个新的数字方块
function spawn() {
let empty = countEmpty();
if (empty === 0) return;
let index = Math.floor(Math.random() * empty); // 随机选一个空闲位置
let value = Math.random() < 0.9 ? 2 : 4; // 随机生成新方块的值
let count = 0;
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (board[i][j] === 0) {
if (count === index) {
board[i][j] = value; // 在选中的位置放上新方块
boxes[i * 4 + j].innerText = value; // 更新对应DOM元素
return;
}
count++;
}
}
}
}
// 更新分数
function updateScore(score) {
scoreDisplay.innerText = score;
}
// 初始化游戏
function initGame() {
if (gameStarted) { return }
gameStarted = true;
board = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
];
updateScore(0);
boxes.forEach(box => {
box.innerText = "";
});
spawn(); // 随机生成两个方块
spawn();
updateBoard();
// startButton.style.display = "none"; // 隐藏开始游戏按钮
// resetButton.style.display = "inline-block"; // 显示重置按钮
}
// 重置游戏
function resetGame() {
scoreDisplay.innerText = "0";
board = Array.from({ length: 4 }, () => Array.from({ length: 4 }, () => 0));
spawn();
spawn();
updateBoard();
location.reload();
}
// 检查游戏是否结束
function checkGameOver() {
let empty = countEmpty();
if (empty > 0)
return false; // 如果还有空位置,游戏继续
// 如果没有空位置,检查是否有相邻的方块值相同的情况,有的话游戏继续,否则游戏结束
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (i < 3 && board[i][j] === board[i + 1][j]) return false;
if (j < 3 && board[i][j] === board[i][j + 1]) return false;
}
}
return true;
}
// 声明全局变量 selectedSquare 来保存当前选中的方块 ID
let selectedSquare = null;
// 为每个方块添加点击事件监听器,用于选中该方块
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
const squareId = "square-" + i + "-" + j;
const square = document.getElementById(squareId);
square.addEventListener('click', () => {
// 取消之前选中方块的样式
if (selectedSquare) {
const prevSquare = document.getElementById(selectedSquare);
prevSquare.classList.remove('selected');
}
// 设置当前方块为选中状态,并保存它的 ID 到 selectedSquare 变量中
selectedSquare = squareId;
square.classList.add('selected');
});
}
}
// 移动方块,返回是否有移动
function move(direction) {
let moved = false;
switch (direction) {
case "up":
for (let j = 0; j < 4; j++) {
for (let i = 1; i < 4; i++) {
const squareId = "square-" + i + "-" + j;
if (board[i][j] !== 0 && (selectedSquare === null || squareId === selectedSquare)) { // 只处理玩家选中的方块
let x = i;
while (x > 0 && board[x - 1][j] === 0) {
board[x - 1][j] = board[x][j];
board[x][j] = 0;
moved = true;
x--;
}
if (x > 0 && board[x][j] === board[x - 1][j]) {
board[x - 1][j] *= 2;
board[x][j] = 0;
updateScore(Number(scoreDisplay.innerText) + board[x - 1][j]);
moved = true;
}
}
}
}
break;
case "down":
for (let j = 0; j < 4; j++) {
for (let i = 2; i >= 0; i--) {
const squareId = "square-" + i + "-" + j;
if (board[i][j] !== 0 && (selectedSquare === null || squareId === selectedSquare)) { // 只处理玩家选中的方块
let x = i;
while (x < 3 && board[x + 1][j] === 0) {
board[x + 1][j] = board[x][j];
board[x][j] = 0;
moved = true;
x++;
}
if (x < 3 && board[x][j] === board[x + 1][j]) {
board[x + 1][j] *= 2;
board[x][j] = 0;
updateScore(Number(scoreDisplay.innerText) + board[x + 1][j]);
moved = true;
}
}
}
}
break;
case "left":
for (let i = 0; i < 4; i++) {
for (let j = 1; j < 4; j++) {
const squareId = "square-" + i + "-" + j;
if (board[i][j] !== 0 && (selectedSquare === null || squareId === selectedSquare)) { // 只处理玩家选中的方块
let y = j;
while (y > 0 && board[i][y - 1] === 0) {
board[i][y - 1] = board[i][y];
board[i][y] = 0;
moved = true;
y--;
}
if (y > 0 && board[i][y] === board[i][y - 1]) {
board[i][y - 1] *= 2;
board[i][y] = 0;
updateScore(Number(scoreDisplay.innerText) + board[i][y - 1]);
moved = true;
}
}
}
}
break;
case "right":
for (let i = 0; i < 4; i++) {
for (let j = 2; j >= 0; j--) {
const squareId = "square-" + i + "-" + j;
if (board[i][j] !== 0 && (selectedSquare === null || squareId === selectedSquare)) { // 只处理玩家选中的方块
let y = j;
while (y < 3 && board[i][y + 1] === 0) {
board[i][y + 1] = board[i][y];
board[i][y] = 0;
moved = true;
y++;
}
if (y < 3 && board[i][y] === board[i][y + 1]) {
board[i][y + 1] *= 2;
board[i][y] = 0;
updateScore(Number(scoreDisplay.innerText) + board[i][y + 1]);
moved = true;
}
}
}
}
break;
}
return moved;
}
// 更新方块盘面
function updateBoard() {
boxes.forEach((box, index) => {
let row = Math.floor(index / 4);
let col = index % 4;
box.innerText = board[row][col] === 0 ? "" : board[row][col]; // 更新对应DOM元素
});
}
// 监听键盘事件
document.addEventListener("keydown", event => {
switch (event.key) {
case "ArrowUp":
event.preventDefault();
if (move("up")) {
spawn();
updateBoard();
if (checkGameOver()) {
alert("游戏结束!");
resetButton.click(); // 重置游戏
}
}
break;
case "ArrowDown":
event.preventDefault();
if (move("down")) {
spawn();
updateBoard();
if (checkGameOver()) {
alert("游戏结束!");
resetButton.click(); // 重置游戏
}
}
break;
case "ArrowLeft":
event.preventDefault();
if (move("left")) {
spawn();
updateBoard();
if (checkGameOver()) {
alert("游戏结束!");
resetButton.click(); // 重置游戏
}
}
break;
case "ArrowRight":
event.preventDefault();
if (move("right")) {
spawn();
updateBoard();
if (checkGameOver()) {
alert("游戏结束!");
resetButton.click(); // 重置游戏
}
}
break;
default:
break;
}
});
// 监听开始游戏按钮点击事件
startButton.addEventListener("click", () => {
startButton.style.display = "none"; // 隐藏开始游戏按钮
resetButton.style.display = "inline-block"; // 显示重置按钮
gameStarted = false; // 控制是否开启游戏,false开启 true结束
initGame()
});
// 监听重置按钮点击事件
resetButton.addEventListener("click", () => {
resetGame(); // 重置游戏
});
// 初始化游戏
initGame();
游戏运行效果
移动端(玩法:直接移动方块)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>2048</title>
<style>
.game-board {
position: relative;
margin: 16px auto;
width: 90vw;
height: 90vw;
max-width: 500px;
max-height: 500px;
background-color: #bbada0;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4);
overflow: hidden;
}
.square {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
font-size: 32px;
font-weight: bold;
color: white;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
user-select: none;
-webkit-user-select: none;
}
.color-2 {
background-color: #eee4da;
}
.color-4 {
background-color: #ede0c8;
}
.color-8 {
background-color: #f2b179;
}
.color-16 {
background-color: #f59563;
}
.color-32 {
background-color: #f67c5f;
}
.color-64 {
background-color: #f65e3b;
}
.color-128 {
background-color: #edcf72;
}
.color-256 {
background-color: #edcc61;
}
.color-512 {
background-color: #edc850;
}
.color-1024 {
background-color: #edc53f;
}
.color-2048 {
background-color: #edc22e;
}
.restart {
margin: 8px;
font-size: 24px;
font-weight: bold;
color: white;
background-color: #8f7a66;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
padding: 8px 16px;
cursor: pointer;
user-select: none;
-webkit-user-select: none;
}
.score {
margin: 8px;
font-size: 24px;
font-weight: bold;
color: pink;
user-select: none;
-webkit-user-select: none;
}
</style>
</head>
<body>
<div class="game-board"></div>
<button class="restart">重新开始</button>
<div class="score-label">得分:</div>
<div class="score" id="score">0</div>
<script>
// 获取设备屏幕的宽度和高度
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
// 根据屏幕尺寸计算方块大小、间距等参数
let squareSize = Math.min(screenWidth, screenHeight) * 0.2;
let marginSize = Math.min(screenWidth, screenHeight) * 0.05;
// 初始化游戏
function init() {
// 根据屏幕尺寸计算方块数量、大小、间距等参数
if (screenWidth < 500) {
size = 3;
} else if (screenWidth < 700) {
size = 4;
} else {
size = 5;
}
squareSize = Math.min(screenWidth, screenHeight) * 0.2;
marginSize = Math.min(screenWidth, screenHeight) * 0.05;
// 清空游戏面板和方块数组
gameBoard.innerHTML = "";
squares = [];
// 初始化分数和最高分
let scoreDOM = document.querySelector(".score");
// 创建方块数组和 DOM 元素,并随机生成两个方块的值
for (let row = 0; row < size; row++) {
squares.push([]);
for (let col = 0; col < size; col++) {
const square = createSquare(row, col, "");
squares[row].push(square);
}
}
generateTile();
generateTile();
}
// 创建方块
function createSquare(row, col, value) {
const square = document.createElement("div");
square.className = "square";
square.style.width = squareSize + "px";
square.style.height = squareSize + "px";
square.style.top = row * (squareSize + marginSize) + marginSize + "px";
square.style.left = col * (squareSize + marginSize) + marginSize + "px";
square.textContent = value;
gameBoard.appendChild(square);
return square;
}
// 移动方块
function move(fromRow, fromCol, toRow, toCol) {
const fromSquare = squares[fromRow][fromCol];
const toSquare = squares[toRow][toCol];
toSquare.textContent = fromSquare.textContent;
toSquare.classList.remove(`color-${fromSquare.textContent}`);
toSquare.classList.add(`color-${toSquare.textContent}`);
fromSquare.textContent = "";
fromSquare.classList.remove(`color-${fromSquare.textContent}`);
}
const scoreDisplay = document.getElementById("score");
let score = 0;
// 合并方块
function merge(row1, col1, row2, col2) {
let value = parseInt(squares[row1][col1].textContent) + parseInt(squares[row2][col2].textContent);
squares[row2][col2].textContent = value;
squares[row1][col1].textContent = "";
squares[row2][col2].classList.remove(`color-${squares[row2][col2].textContent}`);
squares[row2][col2].classList.add(`color-${value}`);
score += value; // 更新玩家得分
scoreDisplay.textContent = score; // 在得分面板中显示新得分
}
document.addEventListener('touchmove', function (event) {
event.preventDefault();
}, { passive: false });
function getEmptySquares() {
const emptySquares = [];
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
if (squares[row][col].textContent === "") {
emptySquares.push({ row, col });
}
}
}
return emptySquares;
}
function setSquareValue(row, col, value) {
squares[row][col].textContent = value;
squares[row][col].classList.add(`color-${value}`);
}
// 在随机位置生成一个方块
function generateTile() {
const emptySquares = getEmptySquares();
if (emptySquares.length > 0) {
const index = Math.floor(Math.random() * emptySquares.length);
const square = emptySquares[index];
const value = Math.random() < 0.9 ? 2 : 4;
setSquareValue(square.row, square.col, value);
}
}
let isGameOver = false
let ROWS = 4;
let COLS = 4;
let squares = [];
function createBoard() {
for (let i = 0; i < ROWS; i++) {
squares[i] = [];
for (let j = 0; j < COLS; j++) {
const square = document.createElement("div");
square.classList.add("square");
square.textContent = "";
document.getElementById("board").appendChild(square);
squares[i].push(square);
}
}
}
// 检查游戏是否结束
function checkGameOver() {
let isGameOver = true;
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
if (squares[i][j].textContent === "") {
isGameOver = false;
break;
}
if (j < COLS - 1 && squares[i][j].textContent === squares[i][j + 1].textContent) {
isGameOver = false;
break;
}
if (i < ROWS - 1 && squares[i][j].textContent === squares[i + 1][j].textContent) {
isGameOver = false;
break;
}
}
}
if (isGameOver) {
// 游戏结束,弹出消息框
alert("Game over!");
}
}
// 重新开始游戏
function restart() {
location.reload();
score = 0;
scoreDisplay.innerText = 0;
init();
}
const gameBoard = document.querySelector(".game-board");
// 监听触摸事件
let startRow, startCol;
gameBoard.addEventListener("touchstart", event => {
startRow = Math.floor((event.touches[0].clientY - marginSize) / (squareSize + marginSize));
startCol = Math.floor((event.touches[0].clientX - marginSize) / (squareSize + marginSize));
});
function handleMove(direction) {
if (!isGameOver) {
let hasMoved = false;
switch (direction) {
case "up":
for (let col = 0; col < size; col++) {
for (let row = 1; row < size; row++) {
if (squares[row][col].textContent !== "") {
let currentRow = row;
while (currentRow > 0 && squares[currentRow - 1][col].textContent === "") {
move(currentRow, col, currentRow - 1, col);
currentRow--;
hasMoved = true;
}
if (currentRow > 0 && squares[currentRow - 1][col].textContent === squares[currentRow][col].textContent) {
merge(currentRow, col, currentRow - 1, col);
hasMoved = true;
}
}
}
}
break;
case "down":
for (let col = 0; col < size; col++) {
for (let row = size - 2; row >= 0; row--) {
if (squares[row][col].textContent !== "") {
let currentRow = row;
while (currentRow < size - 1 && squares[currentRow + 1][col].textContent === "") {
move(currentRow, col, currentRow + 1, col);
currentRow++;
hasMoved = true;
}
if (currentRow < size - 1 && squares[currentRow + 1][col].textContent === squares[currentRow][col].textContent) {
merge(currentRow, col, currentRow + 1, col);
hasMoved = true;
}
}
}
}
break;
case "left":
for (let row = 0; row < size; row++) {
for (let col = 1; col < size; col++) {
if (squares[row][col].textContent !== "") {
let currentCol = col;
while (currentCol > 0 && squares[row][currentCol - 1].textContent === "") {
move(row, currentCol, row, currentCol - 1);
currentCol--;
hasMoved = true;
}
if (currentCol > 0 && squares[row][currentCol - 1].textContent === squares[row][currentCol].textContent) {
merge(row, currentCol, row, currentCol - 1);
hasMoved = true;
}
}
}
}
break;
case "right":
for (let row = 0; row < size; row++) {
for (let col = size - 2; col >= 0; col--) {
if (squares[row][col].textContent !== "") {
let currentCol = col;
while (currentCol < size - 1 && squares[row][currentCol + 1].textContent === "") {
move(row, currentCol, row, currentCol + 1);
currentCol++;
hasMoved = true;
}
if (currentCol < size - 1 && squares[row][currentCol + 1].textContent === squares[row][currentCol].textContent) {
merge(row, currentCol, row, currentCol + 1);
hasMoved = true;
}
}
}
}
break;
default:
break;
}
// 如果移动了方块,就生成新的方块
if (hasMoved) {
generateTile();
checkGameOver();
}
}
}
gameBoard.addEventListener("touchend", event => {
const endRow = Math.floor((event.changedTouches[0].clientY - marginSize) / (squareSize + marginSize));
const endCol = Math.floor((event.changedTouches[0].clientX - marginSize) / (squareSize + marginSize));
const distanceRow = endRow - startRow;
const distanceCol = endCol - startCol;
if (Math.abs(distanceRow) > Math.abs(distanceCol)) {
if (distanceRow < 0) {
handleMove("up");
} else if (distanceRow > 0) {
handleMove("down");
}
} else {
if (distanceCol < 0) {
handleMove("left");
} else if (distanceCol > 0) {
handleMove("right");
}
}
});
// 初始化游戏
init();
// 绑定“重新开始”按钮的点击事件
document.querySelector(".restart").addEventListener("click", () => {
restart();
});
</script>
</body>
</html>
效果图