如何修改JavaScript游戏代码实现多小球随机同时持续显示?
实现多小球同时随机持续显示的修改方案
关键问题修正与优化
你的原代码里复用了同一个全局img元素,每次调用createImage只是修改这个元素的属性和位置,所以页面上永远只会显示一个小球。下面是修改后的完整代码,同时优化了小球的生成逻辑和生命周期:
修改后的JavaScript代码
// Declaring the images to use var imagesArray = ["./green-ball.png","./yellow-ball.png","./blue-ball.png","./light-pink-ball.png","./purple-ball.png",]; // Declaring the starting points let score = 0; let timer = 15; var spawnInterval; let timeLeft = 15; let lastScore = 0; // Setting game and images var game = document.getElementById("game"); const scoreElement = document.getElementById("score"); const timerElement = document.getElementById("timer"); // Game over function - clearing the info and resetting variables and updating the last score function gameOver() { var lastScoreElement = document.getElementById("lastScore"); clearInterval(timer); clearInterval(spawnInterval); $("#playAgainButton").show(); $("#lastScore").show( lastScoreElement.textContent = " " + score ); ResetGlobalVariables(); } // Making the random function function random(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } //Creating the images to show up in random positions function createImage() { // 每次创建新的img元素,不再复用全局变量 var img = document.createElement("img"); img.src = imagesArray[random(0, imagesArray.length - 1)]; img.width = random(50, 200); img.height = random(50, 200); img.style.left = random(0, 800 - img.width) + "px"; img.style.top = random(0, 600 - img.height) + "px"; // 给小球添加绝对定位,确保能在游戏区域内随机摆放 img.style.position = "absolute"; img.alt = img.src.split('/').pop(); // to show the colour // 让小球自动消失(避免页面元素堆积) setTimeout(() => { if (img.parentNode) { img.parentNode.removeChild(img); } }, random(2000, 5000)); // 2-5秒后自动消失 return img; } // Creating the updateTimer function - once timer runs out, game is over function updateTimer() { timeLeft = timeLeft - 1; if(timeLeft >= 0) $("#timer").html(timeLeft); else { gameOver(); }; } // Creating the start of the game - setting the timer and creating the balls function start() { // 清空游戏区域的旧小球 game.innerHTML = ""; timer = setInterval(updateTimer, 1000); updateTimer(); $("#playAgainButton").hide(); // 随机间隔生成小球(500-1500毫秒),让出现更随机 spawnInterval = setInterval(function() { var img = createImage(); game.appendChild(img); }, random(500, 1500)); } // Function to reset the global variables - clean slate function ResetGlobalVariables() { score = 0; scoreElement.innerHTML = "Current Score: " + score; timer = 15; timerElement.innerHTML = timer; timeLeft = 15; // 重置时清空游戏区域 game.innerHTML = ""; } // Update when the reset button is clicked const resetBtn = document.querySelector(".reset-button") resetBtn.addEventListener("click", ResetGlobalVariables) // Add event listener - if the ball is green update the score, if the ball is any other colour lose a point game.addEventListener("click", function(e) { const tgt = e.target; if (!tgt.matches('img')) return; // not a ball // 点击后移除小球 tgt.parentNode.removeChild(tgt); if (!tgt.src.includes('green')) score--; // not green else score++; scoreElement.innerHTML = "Current Score: " + score; });
HTML代码(新增游戏区域样式,其余保持原代码)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Find Greenie</title> <link rel="stylesheet" href="find.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <style> /* 给游戏区域添加相对定位,确保小球的绝对定位生效 */ #game { width: 800px; height: 600px; border: 1px solid #000; position: relative; overflow: hidden; } </style> </head> <body> <table> <tr> <td> <div id="game"></div> </td> <td id="text"> <p id="gameTitle">Find Greenie!<img src="green-ball.png" alt="Logo"></p> <p id="score">Current Score: 0</p> <p> You have: <span id="timer">15</span> seconds remaining!</p> <button id="playAgainButton" onclick="start()">Go!</button> <input id="reset" type="button" class="reset-button" value="Reset"> <p> You scored: <span id="lastScore"></span></p> <br> <br> <p>Click on Greenie the green ball to score points</p> <p>But click on any other ball and lose a point!</p> <p>Click Reset and then Go! to restart</p> <script src="find.js"></script> </td> </tr> </table> </body> </html>
关键修改点说明
移除全局
img变量,每次创建新元素
原代码里全局的img被反复修改属性,导致页面始终只有一个小球。现在每次调用createImage都新建一个<img>,这样就能同时显示多个。给小球添加绝对定位
在createImage里给img加上position: absolute,同时给游戏区域#game加上相对定位,这样小球的left和top才能相对于游戏区域定位。随机生成间隔
把原固定的1500毫秒生成间隔,改成random(500,1500),让小球出现的时间更随机,游戏难度更高。小球自动消失+点击后移除
- 给每个小球加了2-5秒的自动消失定时器,避免页面小球堆积导致卡顿
- 点击小球后立即移除,避免重复点击
重置和开始游戏时清空游戏区域
在start和ResetGlobalVariables里添加game.innerHTML = "",确保每次开始/重置游戏时,旧的小球都被清除。
内容的提问来源于stack exchange,提问作者sunseteagle
相关产品推荐
相关产品推荐

