科学教育
标题:
马紫萱
[打印本页]
作者:
马紫萱2
时间:
2025-12-10 15:09
标题:
马紫萱
const canvas = document.getElementById("gameCanvas");
const context = canvas.getContext("2d");
const startButton = document.getElementById("startButton");
const gridSize = 20;
let snake = [];
let food = {x: 0, y: 0};
let dx = gridSize;
let dy = 0;
let score = 0;
let game; // 定时器变量
function drawSnake() {
context.clearRect(0, 0, canvas.width, canvas.height);
snake.forEach(part => {
context.fillStyle = "green";
context.fillRect(part.x, part.y, gridSize, gridSize);
});
}
function generateFood() {
food.x = Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize;
food.y = Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize;
}
function drawFood() {
context.fillStyle = "red";
context.fillRect(food.x, food.y, gridSize, gridSize);
}
function moveSnake() {
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++;
generateFood();
} else {
snake.pop();
}
}
function changeDirection(event) {
const keyPressed = event.key.toLowerCase();
if (keyPressed === 'a' && dx === 0) {
dx = -gridSize;
dy = 0;
}
if (keyPressed === 'w' && dy === 0) {
dx = 0;
dy = -gridSize;
}
if (keyPressed === 'd' && dx === 0) {
dx = gridSize;
dy = 0;
}
if (keyPressed === 's' && dy === 0) {
dx = 0;
dy = gridSize;
}
}
function gameLoop() {
moveSnake();
drawSnake();
drawFood();
if (snake[0].x < 0 || snake[0].x >= canvas.width || snake[0].y < 0 || snake[0].y >= canvas.height) {
clearInterval(game);
alert("Game Over! Your score is " + score);
}
}
startButton.addEventListener("click", () => {
snake = [{x: 100, y: 100}];
dx = gridSize;
dy = 0;
score = 0;
generateFood();
if (game) clearInterval(game); // 防止多次点击start重复启动
game = setInterval(gameLoop, 100);
});
document.addEventListener("keydown", changeDirection);
欢迎光临 科学教育 (http://sci-edu.net/)
Powered by Discuz! X3.2