贪吃蛇小游戏
body {
display: flex;
flex-direction: column;
align-items: center;
background-color: #2c3e50;
color: white;
font-family: Arial, sans-serif;
}
#gameCanvas {
border: 3px solid #34495e;
border-radius: 5px;
background-color: #ecf0f1;
}
#score {
font-size: 2em;
margin: 20px 0;
}
#restart {
padding: 10px 20px;
font-size: 1.2em;
margin-top: 20px;
background-color: #27ae60;
border: none;
color: white;
border-radius: 5px;
cursor: pointer;
}
</style>
得分: 0
重新开始
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const restartButton = document.getElementById('restart');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [{x: 10, y: 10}];
let food = {x: 15, y: 15};
let dx = 0;
let dy = 0;
let score = 0;
let gameLoop;
document.addEventListener('keydown', (e) => {
switch(e.key) {
case 'ArrowUp':
if (dy === 0) { dx = 0; dy = -1; }
break;
case 'ArrowDown':
if (dy === 0) { dx = 0; dy = 1; }
break;
case 'ArrowLeft':
if (dx === 0) { dx = -1; dy = 0; }
break;
case 'ArrowRight':
if (dx === 0) { dx = 1; dy = 0; }
break;
}
});
function drawGame() {
// 移动蛇
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreElement.textContent = `得分: ${score}`;
generateFood();
} else {
snake.pop();
}
// 清空画布
ctx.fillStyle = '#ecf0f1';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制食物
ctx.fillStyle = '#e74c3c';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-2, gridSize-2);
// 绘制蛇
snake.forEach((segment, index) => {
ctx.fillStyle = index === 0 ? '#2ecc71' : '#27ae60';
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize-2, gridSize-2);
});
// 碰撞检测
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount ||
snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)) {
gameOver();
}
}
function generateFood() {
do {
food.x = Math.floor(Math.random() * tileCount);
food.y = Math.floor(Math.random() * tileCount);
} while (snake.some(segment => segment.x === food.x && segment.y === food.y));
}
function gameOver() {
clearInterval(gameLoop);
alert(`游戏结束!得分:${score}`);
}
restartButton.addEventListener('click', () => {
snake = [{x: 10, y: 10}];
dx = 0;
dy = 0;
score = 0;
scoreElement.textContent = '得分: 0';
generateFood();
gameLoop = setInterval(drawGame, 100);
});
// 开始游戏
generateFood();
gameLoop = setInterval(drawGame, 100);
</script>