
最经典的街机游戏之一,今天用纯HTML+CSS+JavaScript从零实现一个功能完整的贪吃蛇。
🎮 方向键控制蛇的移动,吃掉食物变长,碰到墙壁或自己就结束。代码约140行,支持键盘+触屏双操控!
📋 完整源码(复制保存为 snake.html)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>贪吃蛇 - HTML小游戏</title>
<style>
* { margin:0;padding:0;box-sizing:border-box; }
body{background:#1a1a2e;display:flex;justify-content:center;align-items:center;min-height:100vh;font-family:"Segoe UI",sans-serif;color:#eee;flex-direction:column}
h1{margin-bottom:10px;color:#e94560;font-size:28px}
#score{font-size:20px;margin-bottom:10px;color:#0ff}
canvas{border:3px solid #e94560;border-radius:8px;background:#0f3460}
button{background:#e94560;color:white;border:none;padding:10px 24px;font-size:16px;border-radius:6px;cursor:pointer;margin-top:12px;margin:4px}
.tip{color:#aaa;font-size:13px;margin-top:8px}
</style>
</head>
<body>
<h1>🐍 贪吃蛇</h1>
<div id="score">得分:0</div>
<canvas id="game" width="400" height="400"></canvas>
<p class="tip">方向键 ↑↓←→ 控制方向,空格键暂停</p>
<button onclick="startGame()">开始游戏</button>
<script>
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var gridSize = 20;
var tileCount = canvas.width / gridSize;
var snake, food, dx, dy, score, gameLoop, isRunning, isPaused;
function startGame() {
if (gameLoop) clearInterval(gameLoop);
snake = [{x:10,y:10},{x:9,y:10},{x:8,y:10}];
dx = 1; dy = 0; score = 0; isRunning = true; isPaused = false;
placeFood();
document.getElementById("score").textContent = "得分:0";
gameLoop = setInterval(update, 120);
}
function placeFood() {
food = { x: Math.floor(Math.random()*tileCount), y: Math.floor(Math.random()*tileCount) };
for (var s of snake) { if(s.x===food.x && s.y===food.y){placeFood();return;} }
}
function update() {
if(isPaused) return;
var head = { x: snake[0].x+dx, y: snake[0].y+dy };
if(head.x<0||head.x>=tileCount||head.y<0||head.y>=tileCount){gameOver();return;}
for(var s of snake){if(s.x===head.x&&s.y===head.y){gameOver();return;}}
snake.unshift(head);
if(head.x===food.x&&head.y===food.y){score+=10;document.getElementById("score").textContent="得分:"+score;placeFood();}else{snake.pop();}
draw();
}
function draw() {
ctx.fillStyle="#0f3460";ctx.fillRect(0,0,canvas.width,canvas.height);
snake.forEach(function(s,i){
ctx.fillStyle = i===0 ? "#ff6b6b" : "#2ecc71";
ctx.beginPath();ctx.roundRect(s.x*gridSize+1,s.y*gridSize+1,gridSize-2,gridSize-2,4);ctx.fill();
});
ctx.fillStyle="#e94560";ctx.beginPath();ctx.arc(food.x*gridSize+gridSize/2,food.y*gridSize+gridSize/2,gridSize/2-2,0,Math.PI*2);ctx.fill();
}
function gameOver() {
clearInterval(gameLoop);isRunning=false;
ctx.fillStyle="rgba(0,0,0,0.7)";ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle="#e94560";ctx.font="bold 36px sans-serif";ctx.textAlign="center";
ctx.fillText("游戏结束!",canvas.width/2,canvas.height/2-20);
ctx.fillStyle="#fff";ctx.font="24px sans-serif";ctx.fillText("得分:"+score,canvas.width/2,canvas.height/2+20);
}
function togglePause(){if(!isRunning)return;isPaused=!isPaused;}
document.addEventListener("keydown",function(e){
if(e.key===" "){e.preventDefault();togglePause();return;}
var keys={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};
if(keys[e.key]){e.preventDefault();var n=keys[e.key];if(!(n[0]===-dx&&n[1]===-dy)){dx=n[0];dy=n[1];}}
});
// Mobile touch support
var tX,tY;
canvas.addEventListener("touchstart",function(e){tX=e.touches[0].clientX;tY=e.touches[0].clientY;});
canvas.addEventListener("touchend",function(e){
var dX=e.changedTouches[0].clientX-tX,dY=e.changedTouches[0].clientY-tY;
if(Math.abs(dX)>Math.abs(dY)){dx=dX>0?1:-1;dy=0;}else{dy=dY>0?1:-1;dx=0;}
});
startGame();
</script></body></html>
🎯 玩法说明
- 方向键 ↑↓←→:控制蛇的移动方向
- 空格键:暂停/继续游戏
- 手机触屏:在画布上滑动控制方向
- 吃到红色食物得10分,蛇身变长
- 撞到墙壁或自己则游戏结束
🔧 核心技术点
| 技术 | 说明 |
|---|---|
| Canvas 2D | 用 roundRect 绘制圆角蛇身和圆形食物 |
| setInterval 游戏循环 | 每120ms更新一帧,控制蛇移动速度 |
| 碰撞检测 | 检查蛇头是否超出边界或碰到自身 |
| 双端操控 | 键盘按键 + 触屏滑动事件同时支持 |
📥 保存为 snake.html,双击用浏览器打开即可开玩!
原文链接:https://www.rmbxz.com/6532/,转载请注明出处。

请先 !