canvas {
border: 3px solid 4CAF50;
background: 000;
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: f0f0f0;
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
let snake = [{x: 200, y: 200}];
let food = {x: 0, y: 0};
let dx = gridSize;
let dy = 0;
let score = 0;
function createFood {
food.x = Math.floor(Math.random (canvas.width/gridSize)) gridSize;
food.y = Math.floor(Math.random (canvas.height/gridSize)) gridSize;
function gameLoop {
const head = {x: snake.x + dx, y: snake.y + dy};
if (head.x< 0 || head.x >= canvas.width || head.y< 0 || head.y >= canvas.height ||
snake.some(segment => segment.x === head.x && segment.y === head.y)) {
alert('游戏结束!得分: ' + score);
location.reload;
return;
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
createFood;
} else {
snake.pop;
ctx.fillStyle = '000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '4CAF50';
snake.forEach(segment => {
ctx.fillRect(segment.x, segment.y, gridSize-1, gridSize-1);
});
ctx.fillStyle = 'FF0000';
ctx.fillRect(food.x, food.y, gridSize-1, gridSize-1);
setTimeout(gameLoop, 100);
document.addEventListener('keydown', (e) => {
switch(e.key) {
case 'ArrowUp': if (dy === 0) { dx = 0; dy = -gridSize; } break;
case 'ArrowDown': if (dy === 0) { dx = 0; dy = gridSize; } break;
case 'ArrowLeft': if (dx === 0) { dx = -gridSize; dy = 0; } break;
case 'ArrowRight': if (dx === 0) { dx = gridSize; dy = 0; } break;
});
createFood;
gameLoop;
```
郑重声明:
以上内容均源自于网络,内容仅用于个人学习、研究或者公益分享,非商业用途,如若侵犯到您的权益,请联系删除,客服QQ:841144146
相关阅读
《永劫无间》新手指南:角色介绍、武器连招及游戏术语解析
2025-09-28 13:33:06资源管理黄金法则与游戏进阶技巧
2025-09-01 18:37:35《攻城掠地》剧情任务解析:深入游戏世界解锁更多故事内容
2025-08-29 12:05:31如何优化《魔兽争霸》的过山车游戏体验
2025-08-25 18:48:58攻城掠地小号流全解析:如何通过多账号协作达到游戏巅峰
2025-08-23 08:10:10