HTML5+css+js制作2048
制作2048游戏涉及到的技术栈包括HTML、CSS和JavaScript。以下是一个简单的2048游戏实现示例:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2048 Game</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="game-container">
<div id="game-message"></div>
<div id="score-container">
<span id="score">0</span>
<button id="restart-button">Restart</button>
</div>
<div id="grid-container">
<!-- Grid will be dynamically generated here -->
</div>
</div>
</body>
</html>
CSS (style.css):
#game-container {
margin: 0 auto;
padding-top: 50px;
width: 400px;
text-align: center;
}
#grid-container {
width: 100%;
margin: 0 auto;
background-color: #bbada0;
border-radius: 4px;
position: relative;
}
.cell {
width: 100px;
height: 100px;
border: 1px solid #ccc;
float: left;
background-color: #ccc;
font-size: 50px;
color: #fff;
line-height: 100px;
box-sizing: border-box;
}
#score-container {
margin-bottom: 20px;
}
#score {
font-size: 24px;
}
#restart-button {
padding: 10px 20px;
margin-left: 5px;
background-color: #bbada0;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#game-message {
font-size: 24px;
color: red;
}
JavaScript (script.js):
const gridSize = 4; // 可以修改为 3 或 5 等
const winScore = 2048;
const emptyCellValue = 0;
const generatedValues = [2, 4]; // 游戏开始时生成的两个数字
let gameOver = false;
let score = 0;
let grid = [];
function init() {
// 初始化grid
for (let i = 0; i < gridSize; i++) {
grid.push([]);
for (let j = 0; j < gridSize; j++) {
grid[i].push(emptyCellValue);
}
}
// 随机放入两个数字
let randomIndex = Math.floor(Math.random() * (gridSize ** 2));
grid[randomIndex % gridSize][Math.floor(randomIndex / gridSize)] = generatedValues[Math.floor(Math.random() * generatedValues.length)];
randomIndex = Math.floor(Math.random() * (gridSize ** 2));
grid[randomIndex % gridSize][Math.floor(randomIndex /
评论已关闭