|
|
好的,那我来优化一下这段代码,并添加一个“开始游戏”的按钮。我们将这个按钮放在HTML文件中,通过JavaScript代码控制游戏的开始。
### 1. HTML 文件 (index.html)
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Snake Game</title>
- <link rel="stylesheet" href="styles.css">
- </head>
- <body>
- <div id="gameContainer">
- <canvas id="gameCanvas" width="400" height="400"></canvas>
- <button id="startButton">开始游戏</button>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
### 2. CSS 文件 (styles.css)
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- background-color: #f0f0f0;
- margin: 0;
- font-family: Arial, sans-serif;
- }
- #gameContainer {
- text-align: center;
- }
- canvas {
- border: 2px solid #000;
- background-color: #fff;
- display: block;
- margin: 0 auto 20px auto;
- }
- #startButton {
- padding: 10px 20px;
- font-size: 16px;
- }
复制代码
### 3. JavaScript 文件 (script.js)
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- const startButton = document.getElementById("startButton");
- const gridSize = 20;
- let snake = [];
- let direction = { x: 0, y: 0 };
- let food = { x: 0, y: 0 };
- let score = 0;
- document.addEventListener("keydown", changeDirection);
- startButton.addEventListener("click", startGame);
- function startGame() {
- resetGame();
- gameLoop();
- }
- function gameLoop() {
- if (checkCollision()) {
- alert("Game Over! Your score: " + score);
- resetGame();
- } else {
- moveSnake();
- if (checkFoodCollision()) {
- growSnake();
- placeFood();
- score++;
- }
- clearCanvas();
- drawSnake();
- drawFood();
- setTimeout(gameLoop, 100);
- }
- }
- function clearCanvas() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- }
- function drawSnake() {
- ctx.fillStyle = "green";
- snake.forEach(segment => {
- ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
- });
- }
- function moveSnake() {
- const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
- snake.unshift(head);
- snake.pop();
- }
- function changeDirection(event) {
- switch (event.keyCode) {
- case 37: // left arrow key
- if (direction.x === 0) direction = { x: -gridSize, y: 0 };
- break;
- case 38: // up arrow key
- if (direction.y === 0) direction = { x: 0, y: -gridSize };
- break;
- case 39: // right arrow key
- if (direction.x === 0) direction = { x: gridSize, y: 0 };
- break;
- case 40: // down arrow key
- if (direction.y === 0) direction = { x: 0, y: gridSize };
- break;
- }
- }
- function checkCollision() {
- const head = snake[0];
- if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
- return true;
- }
- for (let i = 1; i < snake.length; i++) {
- if (snake[i].x === head.x && snake[i].y === head.y) {
- return true;
- }
- }
- return false;
- }
- function checkFoodCollision() {
- return snake[0].x === food.x && snake[0].y === food.y;
- }
- function growSnake() {
- const tail = { ...snake[snake.length - 1] };
- snake.push(tail);
- }
- function placeFood() {
- food.x = Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize;
- food.y = Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize;
- }
- function drawFood() {
- ctx.fillStyle = "red";
- ctx.fillRect(food.x, food.y, gridSize, gridSize);
- }
- function resetGame() {
- snake = [
- { x: gridSize * 2, y: 0 },
- { x: gridSize, y: 0 },
- { x: 0, y: 0 }
- ];
- direction = { x: gridSize, y: 0 };
- score = 0;
- placeFood();
- }
复制代码
### 改进内容:
1. **添加开始按钮**:在HTML中添加了一个开始按钮,并使用JavaScript控制游戏的开始。
2. **容器布局调整**:使用CSS给`canvas`和按钮添加了一些样式,使其布局更合理。
3. **编码结构优化**:重构了一些函数和变量,更加清晰易读。
请将以上代码分别复制到`index.html`, `styles.css` 和 `script.js` 文件中,然后打开浏览器中的`index.html`文件即可运行贪吃蛇游戏,并通过点击“开始游戏”按钮来启动游戏。 |
|