<!DOCTYPE html>
<html>
<head>
    <title>4044 游戏:点击消除球球!</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: sans-serif;
            background: #F0F0F0;
        }
        #game-container {
            width: 500px;
            height: 500px;
            position: relative;
            margin: auto;
            background: #FFF;
            box-shadow: 0px 0px 20px 0px #999;
        }
        #score {
            width: 500px;
            height: 30px;
            background: #DDD;
            text-align: center;
            line-height: 30px;
        }
        #board {
            width: 500px;
            height: 460px;
            background: #999;
        }
        .ball {
            width: 40px;
            height: 40px;
            position: absolute;
            background: #F00;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <div id='game-container'>
        <div id='score'></div>
        <div id='board'></div>
    </div>
    <script>
        // Game variables
        var board = document.getElementById('board');
        var score = document.getElementById('score');
        var ballCount = 40;
        var scoreCount = 0;
        var ballArray = [];
<pre><code>    // Create balls 
    for(var i = 0; i &lt; ballCount; i++) {
        var ball = document.createElement('div');
        ball.className = 'ball';

        // Generate random position
        var x = Math.random() * (board.offsetWidth - ball.offsetWidth);
        var y = Math.random() * (board.offsetHeight - ball.offsetHeight);
        ball.style.left = x + 'px';
        ball.style.top = y + 'px';

        // Add to array and board
        ballArray.push(ball);
        board.appendChild(ball);
    }

    // Click event
    board.addEventListener('click', function(e) {
        // Get click position
        var x = e.offsetX;
        var y = e.offsetY;

        // Check if click on a ball
        for(var i = 0; i &lt; ballArray.length; i++) {
            var ball = ballArray[i];

            // Check position
            if (x &gt; ball.offsetLeft &amp;&amp; 
                x &lt; (ball.offsetLeft + ball.offsetWidth) &amp;&amp;
                y &gt; ball.offsetTop &amp;&amp;
                y &lt; (ball.offsetTop + ball.offsetHeight)) {

                // Remove ball
                board.removeChild(ball);
                ballArray.splice(i, 1);

                // Update score
                scoreCount++;
                score.innerHTML = 'Score: ' + scoreCount;

                // Game over
                if (ballArray.length == 0) {
                    alert('Game Over!');
                }
            }
        }
    });
&lt;/script&gt;
</code></pre>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/lf3F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录