文章目录
- 贪吃蛇游戏
- 运行效果
- 代码
贪吃蛇游戏
贪吃蛇是一款经典的休闲益智游戏。本文将通过HTML5和JavaScript详细解析如何实现一个简易版的贪吃蛇游戏。游戏的主要逻辑包括蛇的移动、碰撞检测、食物生成等功能。以下是游戏的完整代码及注释解析。(纯属好玩)
运行效果
代码
<!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><style>body {margin: 0;display: flex;flex-direction: column;justify-content: center;align-items: center;height: 100vh;background-color: #000;}canvas {border: 1px solid #fff;}.mobile-controls {display: flex;justify-content: center;margin-top: 20px;}.control-button {background-color: #fff;border: 1px solid #000;padding: 10px 20px;margin: 5px;font-size: 18px;cursor: pointer;border-radius: 5px;}</style>
</head><body><!-- 画布,用于绘制蛇和食物 --><canvas id="gameCanvas"></canvas><!-- 控制按钮:上下左右,用于移动蛇 --><div class="mobile-controls"><button class="control-button" id="left">左</button><button class="control-button" id="up">上</button><button class="control-button" id="down">下</button><button class="control-button" id="right">右</button></div><script>// 获取画布和上下文const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');// 设置每个方块的大小和游戏区域的行列数const scale = 20;const rows = 20;const columns = 20;// 设置画布的宽高canvas.width = columns * scale;canvas.height = rows * scale;let snake; // 蛇对象let food; // 食物位置let direction = { x: 1, y: 0 }; // 方向,初始为向右let isGameOver = false; // 判断游戏是否结束// 蛇的构造函数function Snake() {this.body = [{ x: 10, y: 10 }]; // 蛇的初始位置(数组,每一节为一个坐标)// 绘制蛇this.draw = function () {ctx.fillStyle = 'green'; // 设置蛇的颜色为绿色for (let i = 0; i < this.body.length; i++) {ctx.fillRect(this.body[i].x * scale, this.body[i].y * scale, scale, scale); // 绘制蛇的每一节}};// 更新蛇的位置this.update = function () {// 新的蛇头位置,根据当前方向生成const newHead = {x: this.body[0].x + direction.x,y: this.body[0].y + direction.y};// 判断蛇是否撞墙或撞到自己if (newHead.x < 0 || newHead.x >= columns || newHead.y < 0 || newHead.y >= rows || this.isCollision(newHead)) {isGameOver = true; // 如果碰撞,游戏结束}// 将新头部添加到蛇的身体this.body.unshift(newHead);// 如果蛇头吃到食物,生成新的食物if (newHead.x === food.x && newHead.y === food.y) {generateFood();} else {// 否则,移除蛇尾,保持蛇的长度this.body.pop();}};// 判断是否撞到自己this.isCollision = function (pos) {for (let i = 0; i < this.body.length; i++) {if (this.body[i].x === pos.x && this.body[i].y === pos.y) {return true;}}return false;};}// 生成食物的位置,随机在网格中生成function generateFood() {food = {x: Math.floor(Math.random() * columns),y: Math.floor(Math.random() * rows)};}// 绘制食物function drawFood() {ctx.fillStyle = 'red'; // 食物颜色为红色ctx.fillRect(food.x * scale, food.y * scale, scale, scale); // 绘制食物}// 游戏主循环function gameLoop() {if (isGameOver) {alert('Game Over'); // 游戏结束提示document.location.reload(); // 重新加载页面,重新开始游戏return;}// 清空画布,绘制新的状态ctx.clearRect(0, 0, canvas.width, canvas.height);snake.update(); // 更新蛇的位置snake.draw(); // 绘制蛇drawFood(); // 绘制食物// 每200毫秒更新一次游戏状态setTimeout(gameLoop, 200); }// 键盘事件监听,使用中文“上、下、左、右”控制蛇的方向window.addEventListener('keydown', (e) => {switch (e.key) {case '上':if (direction.y === 0) direction = { x: 0, y: -1 }; // 向上break;case '下':if (direction.y === 0) direction = { x: 0, y: 1 }; // 向下break;case '左':if (direction.x === 0) direction = { x: -1, y: 0 }; // 向左break;case '右':if (direction.x === 0) direction = { x: 1, y: 0 }; // 向右break;}});// 按钮点击事件,控制蛇的移动方向document.getElementById('left').addEventListener('click', () => {if (direction.x === 0) direction = { x: -1, y: 0 };});document.getElementById('right').addEventListener('click', () => {if (direction.x === 0) direction = { x: 1, y: 0 };});document.getElementById('up').addEventListener('click', () => {if (direction.y === 0) direction = { x: 0, y: -1 };});document.getElementById('down').addEventListener('click', () => {if (direction.y === 0) direction = { x: 0, y: 1 };});// 初始化蛇和食物snake = new Snake();generateFood();gameLoop(); // 开始游戏</script></body></html>