科学教育

标题: 何星辰代码 [打印本页]

作者: 何星辰    时间: 2025-12-9 15:15
标题: 何星辰代码
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.keyCode;
    // 用WASD控制方向
    if (keyPressed === 65 && dx === 0) { // A - 向左
        dx = -gridSize;
        dy = 0;
    }
    if (keyPressed === 87 && dy === 0) { // W - 向上
        dx = 0;
        dy = -gridSize;
    }
    if (keyPressed === 68 && dx === 0) { // D - 向右
        dx = gridSize;
        dy = 0;
    }
    if (keyPressed === 83 && dy === 0) { // S - 向下
        dx = 0;
        dy = gridSize;
    }
}

function gameLoop() {
    moveSnake();
    drawSnake();
    drawFood();

    const head = snake[0];

    // 撞墙判断
    if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
        clearInterval(game);
        alert("Game Over! Your score is " + score);
    }
}

startButton.addEventListener("click", () => {
    snake = [
        {x: 0, y: 0},
        {x: gridSize, y: 0},
        {x: gridSize * 2, y: 0},
    ];
    dx = gridSize;
    dy = 0;
    score = 0;
    generateFood();
    clearInterval(game); // 避免重复启动多个定时器
    game = setInterval(gameLoop, 100);
});

document.addEventListener("keydown", changeDirection);






欢迎光临 科学教育 (http://sci-edu.net/) Powered by Discuz! X3.2