js代码实现贪吃蛇
实现贪吃蛇的基本思路
使用HTML5的Canvas绘制游戏界面,通过JavaScript控制蛇的移动、食物生成和碰撞检测。核心逻辑包括蛇的移动方向控制、身体增长、边界检测和食物交互。
初始化游戏画布和变量
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 food = {x: 5, y: 5};
let xVelocity = 0;
let yVelocity = 0;
let score = 0;
let gameSpeed = 100;
let gameRunning = true;
绘制游戏元素
function drawGame() {
// 清空画布
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制蛇
ctx.fillStyle = 'lime';
snake.forEach(segment => {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize-2, gridSize-2);
});
// 绘制食物
ctx.fillStyle = 'red';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-2, gridSize-2);
// 显示分数
ctx.fillStyle = 'white';
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, 10, 20);
}
更新蛇的位置
function updateSnake() {
const head = {x: snake[0].x + xVelocity, y: snake[0].y + yVelocity};
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
score++;
generateFood();
increaseSpeed();
} else {
snake.pop();
}
}
生成随机食物位置
function generateFood() {
food = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
// 确保食物不会出现在蛇身上
snake.forEach(segment => {
if (segment.x === food.x && segment.y === food.y) {
generateFood();
}
});
}
碰撞检测
function checkCollision() {
const head = snake[0];
// 边界碰撞
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
gameOver();
}
// 自身碰撞
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
}
}
}
键盘控制
document.addEventListener('keydown', (e) => {
// 防止180度转向
switch(e.key) {
case 'ArrowUp':
if (yVelocity !== 1) {
xVelocity = 0;
yVelocity = -1;
}
break;
case 'ArrowDown':
if (yVelocity !== -1) {
xVelocity = 0;
yVelocity = 1;
}
break;
case 'ArrowLeft':
if (xVelocity !== 1) {
xVelocity = -1;
yVelocity = 0;
}
break;
case 'ArrowRight':
if (xVelocity !== -1) {
xVelocity = 1;
yVelocity = 0;
}
break;
}
});
游戏主循环
function gameLoop() {
if (gameRunning) {
updateSnake();
checkCollision();
drawGame();
setTimeout(gameLoop, gameSpeed);
}
}
function gameOver() {
gameRunning = false;
ctx.fillStyle = 'white';
ctx.font = '40px Arial';
ctx.fillText('Game Over!', canvas.width/2 - 100, canvas.height/2);
}
function increaseSpeed() {
if (gameSpeed > 50) {
gameSpeed -= 5;
}
}
// 开始游戏
generateFood();
gameLoop();
HTML结构
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
扩展功能建议
增加游戏开始界面和重新开始按钮 添加不同难度级别 实现高分记录功能 增加特殊食物类型 添加音效和动画效果
这个实现包含了贪吃蛇游戏的基本功能,包括蛇的移动、食物生成、碰撞检测和分数计算。代码结构清晰,易于理解和扩展。







