let snake = [{x: 200, y: 200}];
let food = {x: 10, y: 10};
let direction = {x: 0, y: 0};
let lastDirection = {x: 0, y: 0};
let score = 0;
let highScore = localStorage.getItem('highScore') || 0;
let gameSpeed = 150;
let gameRunning = false;
let gamePaused = false;
let gameLoop;
// 事件监听
document.addEventListener('keydown', e => {
if (!gameRunning || gamePaused) return;
switch(e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (lastDirection.y === 0) direction = {x: 0, y: -1};
break;
case 'ArrowDown':
case 's':
case 'S':
if (lastDirection.y === 0) direction = {x: 0, y: 1};
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (lastDirection.x === 0) direction = {x: -1, y: 0};
break;
case 'ArrowRight':
case 'd':
case 'D':
if (lastDirection.x === 0) direction = {x: 1, y: 0};
break;
}
});