|
|
当然可以!以下是一个简化版的贪吃蛇游戏的网页代码,包含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="style.css">
- </head>
- <body>
- <canvas id="gameCanvas" width="400" height="400"></canvas>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
**CSS(style.css)**
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- background-color: #f0f0f0;
- margin: 0;
- }
- canvas {
- border: 1px solid #000;
- }
复制代码
**JavaScript(script.js)**
- const canvas = document.getElementById('gameCanvas');
- const ctx = canvas.getContext('2d');
- const box = 20;
- let snake = [
- {x: 9 * box, y: 10 * box}
- ];
- let food = {
- x: Math.floor(Math.random()*20) * box,
- y: Math.floor(Math.random()*20) * box
- };
- let score = 0;
- let direction;
- document.addEventListener('keydown', setDirection);
- function setDirection(event) {
- const key = event.keyCode;
- if (key == 37 && direction != 'RIGHT') {
- direction = 'LEFT';
- } else if (key == 38 && direction != 'DOWN') {
- direction = 'UP';
- } else if (key == 39 && direction != 'LEFT') {
- direction = 'RIGHT';
- } else if (key == 40 && direction != 'UP') {
- direction = 'DOWN';
- }
- }
- function draw() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- for (let i = 0; i < snake.length; i++) {
- ctx.fillStyle = i === 0 ? 'green' : 'white';
- ctx.fillRect(snake[i].x, snake[i].y, box, box);
- ctx.strokeStyle = 'red';
- ctx.strokeRect(snake[i].x, snake[i].y, box, box);
- }
- ctx.fillStyle = 'red';
- ctx.fillRect(food.x, food.y, box, box);
- let snakeX = snake[0].x;
- let snakeY = snake[0].y;
- if (direction == 'LEFT') snakeX -= box;
- if (direction == 'UP') snakeY -= box;
- if (direction == 'RIGHT') snakeX += box;
- if (direction == 'DOWN') snakeY += box;
- if (snakeX == food.x && snakeY == food.y) {
- score++;
- food = {
- x: Math.floor(Math.random() * 20) * box,
- y: Math.floor(Math.random() * 20) * box
- };
- } else {
- snake.pop();
- }
- let newHead = { x: snakeX, y: snakeY };
- if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
- clearInterval(game);
- alert('Game Over. Your score: ' + score);
- }
- snake.unshift(newHead);
- ctx.fillStyle = 'black';
- ctx.font = '45px Changa one';
- ctx.fillText(score, box, 1.5 * box);
- }
- function collision(head, array) {
- for (let i = 0; i < array.length; i++) {
- if (head.x == array[i].x && head.y == array[i].y) {
- return true;
- }
- }
- return false;
- }
- let game = setInterval(draw, 100);
复制代码
### 说明
1. **HTML**:一个简单的HTML文件,包含一个`canvas`元素用于绘制游戏界面。
2. **CSS**:样式文件,主要是为了使`canvas`居中,并添加边框。
3. **JavaScript**:包含游戏的核心逻辑,包括初始化蛇和食物的位置,处理方向输入,检测碰撞以及绘制游戏的每一帧。
你可以将这些代码分别保存为三个文件(`index.html`,`style.css`,和`script.js`),然后在浏览器中打开`index.html`来运行游戏。希望你喜欢这个小游戏! |
|