純原生 HTML5 + JavaScript,無任何庫,63 行代碼完整實現貪食蛇核心玩法:移動、轉向、進食、生長、碰撞檢測、遊戲結束重啟。適合初學者理解遊戲循環與 Canvas 繪製基礎。
<!DOCTYPE html>
<html>
<body>
<canvas id="game" width="400" height="400" style="border:1px solid #ccc"></canvas>
<script>
const cvs = document.getElementById('game');
const ctx = cvs.getContext('2d');
const SIZE = 20; // 格子/蛇節大小
const ROWS = cvs.width / SIZE; // 20
const COLS = cvs.height / SIZE; // 20
let snake = [{x: 8, y: 8}]; // 初始蛇身 (格子座標)
let dir = {x: 1, y: 0}; // 初始向右
let food = randomFood();
let score = 0;
let loopId;
// 方向控制:防止 180° 反向
document.onkeydown = e => {
const key = e.keyCode;
if (key === 37 && dir.x !== 1) dir = {x: -1, y: 0}; // 左
else if (key === 38 && dir.y !== 1) dir = {x: 0, y: -1}; // 上
else if (key === 39 && dir.x !== -1) dir = {x: 1, y: 0}; // 右
else if (key === 40 && dir.y !== -1) dir = {x: 0, y: 1}; // 下
};
function randomFood() {
let pos;
do {
pos = {x: Math.floor(Math.random()*COLS), y: Math.floor(Math.random()*ROWS)};
} while (snake.some(s => s.x === pos.x && s.y === pos.y));
return pos;
}
function drawRect(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x*SIZE, y*SIZE, SIZE-1, SIZE-1); // -1 留白間隔
}
function gameLoop() {
// 計算新頭部
const head = {x: snake[0].x + dir.x, y: snake[0].y + dir.y};
// 牆壁碰撞 (穿牆模式可改為模運算)
if (head.x < 0 || head.x >= COLS || head.y < 0 || head.y >= ROWS) return gameOver();
// 自身碰撞
if (snake.some(s => s.x === head.x && s.y === head.y)) return gameOver();
snake.unshift(head); // 新頭部入隊
// 進食檢測
if (head.x === food.x && head.y === food.y) {
score++;
food = randomFood();
} else {
snake.pop(); // 未進食則移除尾部 (保持長度)
}
// 渲染
ctx.clearRect(0, 0, cvs.width, cvs.height);
snake.forEach(s => drawRect(s.x, s.y, '#006699'));
drawRect(food.x, food.y, '#e74c3c');
loopId = setTimeout(gameLoop, 120); // ~8fps 可調速度
}
function gameOver() {
clearTimeout(loopId);
alert(`Game Over! 分數: ${score}`);
location.reload();
}
gameLoop();
</script>
</body>
</html>
SIZE 轉像素[{x,y}, ...],頭部索引 0,unshift 入頭、pop 出尾{x:1,y:0} 代表右,按鍵映射向量,阻擋反向setTimeout 遞歸驅動,每幀:計算→碰撞→更新→渲染localStorage)setTimeout 間隔)head.x = (head.x + COLS) % COLSrequestAnimationFrame + 時間戳固定幀率60 行核心邏輯,涵蓋遊戲開發精髓:狀態機、循環、渲染分離、輸入處理、碰撞檢測。閱讀並修改它,是進入 HTML5 遊戲開發的最佳捷徑。