使用HTML5写一个打地鼠的小游戏

创建一个简单的打地鼠游戏涉及HTML5、CSS和JavaScript。以下是一个基本的示例,你可以在此基础上进行扩展和改进。

1. HTML结构

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>打地鼠游戏</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>打地鼠游戏</h1>
    <div id="gameArea">
        <!-- 地鼠洞 -->
        <div class="hole">
            <div class="mole"></div>
        </div>
        <!-- 你可以添加更多的地鼠洞 -->
    </div>
    <script src="script.js"></script>
</body>
</html>

2. CSS样式 (styles.css)

#gameArea {
    width: 600px;
    height: 400px;
    position: relative;
    background-color: #f0f0f0;
    border: 2px solid #000;
}

.hole {
    width: 100px;
    height: 100px;
    background-color: #888;
    border: 2px solid #000;
    position: absolute;
}

.mole {
    width: 80px;
    height: 80px;
    background-color: brown;
    border-radius: 50%;
    position: absolute;
    bottom: 0;
    left: 10px;
    transform: translateY(100%);
    transition: transform 0.3s;
}

.hole.active .mole {
    transform: translateY(0%);
}

3. JavaScript逻辑 (script.js)

document.addEventListener('DOMContentLoaded', function() {
    const holes = document.querySelectorAll('.hole');
    const mole = document.querySelector('.mole');
    let lastHole;
    let timeUp = false;
    let score = 0;

    function randomTime(min, max) {
        return Math.round(Math.random() * (max - min) + min);
    }

    function randomHole(holes) {
        const idx = Math.floor(Math.random() * holes.length);
        const hole = holes[idx];
        if (hole === lastHole) {
            return randomHole(holes);
        }
        lastHole = hole;
        return hole;
    }

    function showMole() {
        const time = randomTime(500, 1000);
        const hole = randomHole(holes);
        hole.classList.add('active');
        setTimeout(() => {
            hole.classList.remove('active');
            if (!timeUp) showMole();
        }, time);
    }

    function startGame() {
        score = 0;
        timeUp = false;
        showMole();
        setTimeout(() => timeUp = true, 10000); // 游戏持续10秒
    }

    function hitMole(e) {
        if (!e.isTrusted) return; // 防止作弊
        if (e.target.classList.contains('mole')) {
            score++;
            console.log('打中地鼠! 得分:', score);
        }
    }

    holes.forEach(hole => hole.addEventListener('click', hitMole));
    startGame();
});

这个示例创建了一个简单的打地鼠游戏,其中地鼠会随机出现在一个洞穴中,并且玩家可以点击地鼠来增加得分。游戏持续10秒,然后停止。你可以根据需要扩展此示例,例如添加更多的洞穴、改进样式、添加得分板等。

posted @   王铁柱6  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示