JavaScript小游戏

67 阅读1分钟

1. 贪吃蛇(Snake)

// 核心逻辑
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let snake = [{x: 200, y: 200}];
let food = {x: 0, y: 0};
let dx = 20, dy = 0;

function generateFood() {
    food.x = Math.floor(Math.random() * canvas.width / 20) * 20;
    food.y = Math.floor(Math.random() * canvas.height / 20) * 20;
}

function gameLoop() {
    // 移动蛇
    const head = {x: snake[0].x + dx, y: snake[0].y + dy};
    snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        generateFood();
    } else {
        snake.pop();
    }
    
    // 绘制游戏
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    snake.forEach(segment => ctx.fillRect(segment.x, segment.y, 20, 20));
    ctx.fillStyle = "red";
    ctx.fillRect(food.x, food.y, 20, 20);
}

document.addEventListener("keydown", (e) => {
    if (e.key === "ArrowUp") { dx = 0; dy = -20; }
    // 其他方向...
});

setInterval(gameLoop, 100);

2. 记忆翻牌(Memory Game)

// 核心逻辑
const cards = ["A", "A", "B", "B", "C", "C"].sort(() => Math.random() - 0.5);
let flippedCards = [];
let matchedPairs = 0;

function flipCard(index) {
    if (flippedCards.length < 2 && !flippedCards.includes(index)) {
        flippedCards.push(index);
        document.getElementById(`card-${index}`).textContent = cards[index];
        
        if (flippedCards.length === 2) {
            const [a, b] = flippedCards;
            if (cards[a] === cards[b]) {
                matchedPairs++;
                flippedCards = [];
                if (matchedPairs === 3) alert("You Win!");
            } else {
                setTimeout(() => {
                    document.getElementById(`card-${a}`).textContent = "";
                    document.getElementById(`card-${b}`).textContent = "";
                    flippedCards = [];
                }, 1000);
            }
        }
    }
}

3. 打字游戏(Typing Speed Test)

// 核心逻辑
const quotes = ["Hello World", "JavaScript is fun", "Coding is art"];
let startTime;

function startGame() {
    const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
    document.getElementById("quote").textContent = randomQuote;
    startTime = new Date();
}

document.getElementById("input").addEventListener("input", (e) => {
    if (e.target.value === document.getElementById("quote").textContent) {
        const time = (new Date() - startTime) / 1000;
        alert(`Your speed: ${Math.round(e.target.value.length / time)} CPM`);
        startGame();
        e.target.value = "";
    }
});

4. 简易平台跳跃(Doodle Jump Clone)

// 核心逻辑
const player = { x: 100, y: 400, vy: 0 };
const platforms = [{ x: 50, y: 500 }, { x: 200, y: 300 }];

function update() {
    player.y += player.vy;
    player.vy += 0.2; // 重力
    
    // 检测平台碰撞
    platforms.forEach(plat => {
        if (player.y + 50 >= plat.y && player.y < plat.y && 
            player.x + 40 > plat.x && player.x < plat.x + 100) {
            player.vy = -10; // 跳跃
        }
    });
    
    // 绘制游戏
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillRect(player.x, player.y, 40, 50);
    platforms.forEach(plat => ctx.fillRect(plat.x, plat.y, 100, 15));
    requestAnimationFrame(update);
}