贪吃蛇小游戏
by EpicGalaxy1689 lines3.2 KB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇小游戏</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;font-family:system-ui}
body{background:#111;color:#fff;display:flex;flex-direction:column;align-items:center;padding:10px}
#gameCanvas{border:3px solid #39ff14;background:#000}
.info{margin:8px 0;font-size:18px}
.ctrl{margin-top:12px;display:grid;grid-template-columns:60px 60px 60px;gap:6px}
.ctrl button{width:60px;height:60px;font-size:24px;border:none;border-radius:8px;background:#22a745;color:#fff}
</style>
</head>
<body>
<div class="info">分数:<span id="score">0</span></div>
<canvas id="gameCanvas" width="320" height="320"></canvas>
<div class="ctrl">
<div></div><button onclick="设置方向(0,-1)">↑</button><div></div>
<button onclick="设置方向(-1,0)">←</button><button onclick="重新开始()">重置</button><button onclick="设置方向(1,0)">→</button>
<div></div><button onclick="设置方向(0,1)">↓</button><div></div>
</div>
<script>
const 画布 = document.getElementById('gameCanvas');
const 绘图 = 画布.getContext('2d');
const 分数文本 = document.getElementById('score');
const 格子大小 = 16;
const 行列数量 = 画布.width / 格子大小;
let 蛇, 食物, 方向, 下一方向, 分数, 计时器;
function 重置游戏(){
蛇 = [{x:6,y:6}];
方向 = {x:1,y:0};
下一方向 = {...方向};
分数 = 0;
生成食物();
分数文本.textContent = 分数;
clearInterval(计时器);
计时器 = setInterval(更新画面,130);
}
function 生成食物(){
do{
食物 = {x:Math.floor(Math.random()*行列数量),y:Math.floor(Math.random()*行列数量)}
}while(蛇.some(点=>点.x===食物.x&&点.y===食物.y))
}
function 设置方向(dx,dy){
if(方向.x !== -dx || 方向.y !== -dy) 下一方向={x:dx,y:dy};
}
function 更新画面(){
方向={...下一方向};
const 蛇头 = {x:蛇[0].x+方向.x,y:蛇[0].y+方向.y};
//撞墙判断
if(蛇头.x<0||蛇头.y<0||蛇头.x>=行列数量||蛇头.y>=行列数量) return 游戏结束();
//撞到自己
if(蛇.some(点=>点.x===蛇头.x&&点.y===蛇头.y)) return 游戏结束();
蛇.unshift(蛇头);
if(蛇头.x===食物.x&&蛇头.y===食物.y){
分数+=10;
分数文本.textContent=分数;
生成食物();
if(计时器>60) clearInterval(计时器), 计时器=setInterval(更新画面,计时器-4);
}else 蛇.pop();
绘制();
}
function 绘制(){
绘图.fillStyle="#000";绘图.fillRect(0,0,画布.width,画布.height);
绘图.fillStyle="#39ff14";
蛇.forEach(点=>绘图.fillRect(点.x*格子大小,点.y*格子大小,格子大小-1,格子大小-1));
绘图.fillStyle="#ff385c";
绘图.fillRect(食物.x*格子大小,食物.y*格子大小,格子大小-1,格子大小-1);
}
function 游戏结束(){
clearInterval(计时器);
alert(`游戏结束!得分:${分数},点重置再来`);
}
function 重新开始(){ 重置游戏(); }
document.addEventListener('keydown',e=>{
switch(e.key){
case 'ArrowUp':设置方向(0,-1);break;
case 'ArrowDown':设置方向(0,1);break;
case 'ArrowLeft':设置方向(-1,0);break;
case 'ArrowRight':设置方向(1,0);break;
}
})
重置游戏();
</script>
</body>
</html>Game Source: 贪吃蛇小游戏
Creator: EpicGalaxy16
Libraries: none
Complexity: moderate (89 lines, 3.2 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-epicgalaxy16" to link back to the original. Then publish at arcadelab.ai/publish.