|
|
当然可以!以下是将HTML、CSS和JavaScript代码分离后的贪吃蛇游戏。
### 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>贪吃蛇游戏</title>
- <link rel="stylesheet" href="styles.css">
- </head>
- <body>
- <canvas id="gameCanvas" width="400" height="400"></canvas>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
### CSS (`styles.css`)
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- background-color: #f0f0f0;
- }
- canvas {
- border: 1px solid black;
- }
复制代码
### JavaScript (`script.js`)
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- const gridSize = 20;
- const tileCount = canvas.width / gridSize;
- let snake = [{ x: 10, y: 10 }];
- let direction = { x: 1, y: 0 };
- let food = { x: 5, y: 5 };
- let gameOver = false;
- function drawTile(x, y, color) {
- ctx.fillStyle = color;
- ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize);
- }
- function update() {
- if (gameOver) return;
- const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
- // 检查是否撞墙或撞自己
- if (
- head.x < 0 ||
- head.x >= tileCount ||
- head.y < 0 ||
- head.y >= tileCount ||
- snake.some(segment => segment.x === head.x && segment.y === head.y)
- ) {
- gameOver = true;
- alert("游戏结束!");
- return;
- }
- snake.unshift(head);
- // 检查是否吃到食物
- if (head.x === food.x && head.y === food.y) {
- placeFood();
- } else {
- snake.pop();
- }
- }
- function draw() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- snake.forEach(segment => drawTile(segment.x, segment.y, "green"));
- drawTile(food.x, food.y, "red");
- }
- function placeFood() {
- let newFoodPosition;
- while (true) {
- newFoodPosition = {
- x: Math.floor(Math.random() * tileCount),
- y: Math.floor(Math.random() * tileCount)
- };
- if (!snake.some(segment => segment.x === newFoodPosition.x && segment.y === newFoodPosition.y)) {
- break;
- }
- }
- food = newFoodPosition;
- }
- function changeDirection(event) {
- switch (event.key) {
- case "ArrowUp":
- if (direction.y === 0) direction = { x: 0, y: -1 };
- break;
- case "ArrowDown":
- if (direction.y === 0) direction = { x: 0, y: 1 };
- break;
- case "ArrowLeft":
- if (direction.x === 0) direction = { x: -1, y: 0 };
- break;
- case "ArrowRight":
- if (direction.x === 0) direction = { x: 1, y: 0 };
- break;
- }
- }
- document.addEventListener("keydown", changeDirection);
- function gameLoop() {
- update();
- draw();
- setTimeout(gameLoop, 100);
- }
- placeFood();
- gameLoop();
复制代码
将这些代码分别保存到不同的文件中(`index.html`, `styles.css`, `script.js`),然后在浏览器中打开`index.html`即可运行贪吃蛇游戏。如果有需要进一步改进或增加功能,请告诉我! |
|