|
|
好的!我们来实现一个优化版的贪吃蛇游戏,满足以下要求:
1. 开始游戏
2. 重新开始
3. 显示得分
4. 游戏结束提示
5. 游戏速度可调节
6. 背景全黑,按键白底黑字
### 1. HTML 部分
我们需要增加按钮和显示区域,并引入 CSS 和 JavaScript 文件。
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>贪吃蛇游戏</title>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <div id="game-container">
- <canvas id="gameCanvas"></canvas>
- <div id="score">得分: 0</div>
- <div id="controls">
- <button id="startBtn">开始游戏</button>
- <button id="resetBtn">重新开始</button>
- <label for="speed">速度:</label>
- <input type="number" id="speed" min="50" max="500" value="200">
- </div>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
### 2. CSS 部分
设置背景颜色、按钮样式等。
- /* style.css */
- body {
- background-color: black;
- color: white;
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- }
- #game-container {
- text-align: center;
- }
- #gameCanvas {
- border: 1px solid #fff;
- background-color: #000;
- }
- #score {
- font-size: 2em;
- margin-top: 10px;
- }
- #controls {
- margin-top: 20px;
- }
- button, input {
- margin-right: 10px;
- padding: 10px 20px;
- font-size: 1em;
- background-color: white;
- color: black;
- border: none;
- cursor: pointer;
- }
- button:hover, input:hover {
- background-color: black;
- color: white;
- border: 1px solid white;
- }
复制代码
### 3. JavaScript 部分
实现贪吃蛇的主要逻辑和功能。
- // script.js
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- const scoreDisplay = document.getElementById("score");
- const startBtn = document.getElementById("startBtn");
- const resetBtn = document.getElementById("resetBtn");
- const speedInput = document.getElementById("speed");
- const gridSize = 20; // 网格大小
- const canvasSize = 400; // 画布大小
- canvas.width = canvas.height = canvasSize;
- let snake, food, dx, dy, score, gameSpeed, gameInterval;
- startBtn.addEventListener("click", startGame);
- resetBtn.addEventListener("click", resetGame);
- document.addEventListener("keydown", changeDirection);
- function startGame() {
- resetGame();
- main();
- }
- function resetGame() {
- clearInterval(gameInterval);
- snake = [{ x: gridSize * 5, y: gridSize * 5 }];
- dx = gridSize;
- dy = 0;
- score = 0;
- gameSpeed = parseInt(speedInput.value);
- food = generateFood();
- updateScore();
- clearCanvas();
- drawSnake();
- drawFood();
- }
- function main() {
- gameInterval = setInterval(function onTick() {
- if (gameOver()) {
- clearInterval(gameInterval);
- alert('游戏结束!');
- return;
- }
- clearCanvas();
- drawFood();
- moveSnake();
- drawSnake();
- }, gameSpeed);
- }
- function clearCanvas() {
- ctx.fillStyle = "black";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- }
- function drawSnake() {
- ctx.fillStyle = "green";
- snake.forEach(part => {
- ctx.fillRect(part.x, part.y, gridSize, gridSize);
- });
- }
- function moveSnake() {
- const head = { x: snake[0].x + dx, y: snake[0].y + dy };
- snake.unshift(head);
- if (head.x === food.x && head.y === food.y) {
- food = generateFood();
- score += 10;
- updateScore();
- } else {
- snake.pop();
- }
- }
- function drawFood() {
- ctx.fillStyle = "red";
- ctx.fillRect(food.x, food.y, gridSize, gridSize);
- }
- function generateFood() {
- let x, y;
- do {
- x = Math.floor(Math.random() * (canvasSize / gridSize)) * gridSize;
- y = Math.floor(Math.random() * (canvasSize / gridSize)) * gridSize;
- } while (snake.some(part => part.x === x && part.y === y));
- return { x, y };
- }
- function changeDirection(event) {
- const LEFT_KEY = 37;
- const RIGHT_KEY = 39;
- const UP_KEY = 38;
- const DOWN_KEY = 40;
- const keyPressed = event.keyCode;
- const goingUp = dy === -gridSize;
- const goingDown = dy === gridSize;
- const goingRight = dx === gridSize;
- const goingLeft = dx === -gridSize;
- if (keyPressed === LEFT_KEY && !goingRight) {
- dx = -gridSize;
- dy = 0;
- }
- if (keyPressed === UP_KEY && !goingDown) {
- dx = 0;
- dy = -gridSize;
- }
- if (keyPressed === RIGHT_KEY && !goingLeft) {
- dx = gridSize;
- dy = 0;
- }
- if (keyPressed === DOWN_KEY && !goingUp) {
- dx = 0;
- dy = gridSize;
- }
- }
- function gameOver() {
- for (let i = 4; i < snake.length; i++) {
- if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) return true;
- }
- const hitLeftWall = snake[0].x < 0;
- const hitRightWall = snake[0].x >= canvas.width;
- const hitTopWall = snake[0].y < 0;
- const hitBottomWall = snake[0].y >= canvas.height;
- return hitLeftWall || hitRightWall || hitTopWall || hitBottomWall;
- }
- function updateScore() {
- scoreDisplay.textContent = `得分: ${score}`;
- }
- startGame(); // 初次加载页面时自动开始游戏
复制代码
这样,我们就完成了一个功能齐全的贪吃蛇游戏。你可以将上面的代码分别保存到 `index.html`、`style.css` 和 `script.js` 三个文件中,然后在浏览器中打开 `index.html` 就能看到效果了。如果有任何问题,随时问我哦! |
|