想在网页中创建一个经典的20x20像素贪吃蛇游戏?本文提供简洁高效的实现方案,适合开发者快速集成或修改。

使用HTML5 Canvas和JavaScript实现:
``html
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20; // 每个格子20x20像素
`
画布尺寸为400x400,对应20x20网格(400/20=20格)。
蛇身与食物初始化
`javascript
let snake = [{x: 10, y: 10}]; // 初始位置
let food = {x: 15, y: 15};
let direction = 'right';
`
绘制函数
`javascript
function draw {
ctx.fillStyle = '000';
ctx.fillRect(0, 0, canvas.width, canvas.height); // 清空画布
// 绘制蛇
ctx.fillStyle = '0f0';
snake.forEach(segment => ctx.fillRect(segment.xgridSize, segment.ygridSize, gridSize-2, gridSize-2));
// 绘制食物
ctx.fillStyle = 'f00';
ctx.fillRect(food.xgridSize, food.ygridSize, gridSize-2, gridSize-2);
`
移动与碰撞检测
`javascript
function move {
const head = {...snake};
switch(direction) {
case 'up': head.y--; break;
case 'down': head.y++; break;
case 'left': head.x--; break;
case 'right': head.x++; break;
// 边界检测(循环穿越)
if (head.x< 0) head.x = 19;
if (head.x > 19) head.x = 0;
if (head.y< 0) head.y = 19;
if (head.y > 19) head.y = 0;
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
food = {x: Math.floor(Math.random20), y: Math.floor(Math.random20)};
} else {
snake.pop;
`
控制与循环
`javascript
document.addEventListener('keydown', (e) => {
const keyMap = {ArrowUp:'up', ArrowDown:'down', ArrowLeft:'left', ArrowRight:'right'};
if (keyMap[e.key]) direction = keyMap[e.key];
});
setInterval( => { move; draw; }, 200); // 每200ms更新
`
时间间隔控制蛇速变量,每次吃到食物时累加立即尝试:复制代码到HTML文件,用浏览器打开即可体验经典20x20贪吃蛇!支持方向键操控,适配PC与移动端浏览器。
2025-10-25 17:38:27
2025-10-25 17:38:24
2025-10-25 17:37:45
2025-10-25 17:35:32
2025-10-25 17:35:25
2025-10-25 17:34:25
2025-10-25 17:33:19
2025-10-25 17:28:28