|
|
当然可以!下面是一个简单的贪吃蛇网页游戏的基本实现。这将包括HTML、CSS和JavaScript。请按照以下步骤创建你的贪吃蛇游戏:
1. 创建 `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="style.css">
- </head>
- <body>
- <div class="game-container">
- <canvas id="gameCanvas"></canvas>
- <div id="score">Score: 0</div>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
2. 创建 `style.css` 文件:
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- background-color: #f0f0f0;
- }
- .game-container {
- text-align: center;
- }
- #gameCanvas {
- border: 1px solid #000;
- background-color: #fff;
- }
- #score {
- font-size: 24px;
- margin-top: 10px;
- }
复制代码
3. 创建 `script.js` 文件:
- const canvas = document.getElementById('gameCanvas');
- const ctx = canvas.getContext('2d');
- const gridSize = 20;
- const tileCount = 20;
- let snake = [{ x: 10, y: 10 }];
- let direction = { x: 0, y: 0 };
- let apple = { x: 15, y: 15 };
- let score = 0;
- canvas.width = canvas.height = gridSize * tileCount;
- function draw() {
- ctx.fillStyle = 'white';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- ctx.fillStyle = 'red';
- ctx.fillRect(apple.x * gridSize, apple.y * gridSize, gridSize - 2, gridSize - 2);
- ctx.fillStyle = 'green';
- snake.forEach(part => {
- ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize - 2, gridSize - 2);
- });
- requestAnimationFrame(update);
- }
- function update() {
- const nextX = snake[0].x + direction.x;
- const nextY = snake[0].y + direction.y;
- if (nextX === apple.x && nextY === apple.y) {
- score++;
- document.getElementById('score').innerText = `Score: ${score}`;
- apple.x = Math.floor(Math.random() * tileCount);
- apple.y = Math.floor(Math.random() * tileCount);
- } else {
- snake.pop();
- }
- const newHead = { x: nextX, y: nextY };
- if (
- newHead.x < 0 || newHead.x >= tileCount ||
- newHead.y < 0 || newHead.y >= tileCount ||
- snake.some(part => part.x === newHead.x && part.y === newHead.y)
- ) {
- alert("Game Over");
- snake = [{ x: 10, y: 10 }];
- direction = { x: 0, y: 0 };
- score = 0;
- document.getElementById('score').innerText = `Score: ${score}`;
- return;
- }
- snake.unshift(newHead);
- requestAnimationFrame(draw);
- }
- window.addEventListener('keydown', e => {
- switch (e.keyCode) {
- case 37:
- if (direction.x === 0) direction = { x: -1, y: 0 };
- break;
- case 38:
- if (direction.y === 0) direction = { x: 0, y: -1 };
- break;
- case 39:
- if (direction.x === 0) direction = { x: 1, y: 0 };
- break;
- case 40:
- if (direction.y === 0) direction = { x: 0, y: 1 };
- break;
- }
- });
- requestAnimationFrame(draw);
复制代码
将这三个文件放在同一个目录下,然后打开 `index.html` 文件,你就可以玩这个简单的贪吃蛇游戏了。
这个版本只是一个非常基础的实现。如果你想增加更多功能(如不同难度、音效等),可以进一步扩展代码。 |
|