//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。
console.log("Hello world! - js.jsrun.net ");
console.log("Hello world! - js.jsrun.net ");
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
canvas {
border: 1px solid #000;
background-color: #fff;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
let snake = [{ x: 9 * box, y: 9 * box }];
let direction = 'RIGHT';
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
let score = 0;
document.addEventListener('keydown', directionControl);
function directionControl(event) {
if (event.key === 'ArrowUp' && direction !== 'DOWN') direction = 'UP';
if (event.key === 'ArrowDown' && direction !== 'UP') direction = 'DOWN';
if (event.key === 'ArrowLeft' && direction !== 'RIGHT') direction = 'LEFT';
if (event.key === 'ArrowRight' && direction !== 'LEFT') direction = 'RIGHT';
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'lightgreen';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'darkgreen';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
ctx.fillStyle = 'black';
ctx.fillText(`分数: ${score}`, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'LEFT') snakeX -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'UP') snakeY -= box;
if (direction === 'DOWN') snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
score++;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
let newHead = { x: snakeX, y: snakeY };
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
alert("游戏结束!");
}
snake.unshift(newHead);
}
let game = setInterval(draw, 100);
</script>
</body>
</html>