如何为JavaScript小游戏添加重置/重新开始功能?
Hey there! Let's get that restart button working for your space game. Here's the modified code with the reset button added, plus fixes to make it properly restart the game when clicked:
Modified Full Code
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <style> canvas { border:7px solid #00aaff; background-color: #00aaff; } button { margin: 10px 0; } </style> </head> <body onload="startGame()"> <br> <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)"> <p style="font-family:Wide Latin"><font color="#00aaff">Click to Accelerate</font></p> </button> <!-- New Restart Button --> <button onclick="resetGame()"> <p style="font-family:Wide Latin"><font color="#ff4444">Restart Game</font></p> </button> <p style="font-family:Arial Rounded MT Bold; color:turquoise"> ☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️Click the ACCELERATE button to start the game☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️☄️ </p> <p style="font-family:Agency FB; color:Orange"> 🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀How long can you stay alive? Use the ACCELERATE button to stay in the air.🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀 </p> <script> var myGamePiece; var myBackground; var myObstacles = []; var myScore; var gameSpeed = 1; function startGame() { myBackground = new component(800, 380,"http://static.giantbomb.com/uploads/original/29/297846/2789895-cool+space+backgrounds+desktop+hd+wallpaper.jpg", 0, 0, "image"); myGamePiece = new component(50, 50, "http://images.tourismholdings.com/public/2016/02/56bd3c714ecc6.png", 35, 200, "image"); myScore = new component("30px", "Algerian", "turquoise", 15, 30, "text"); myGameArea.start(); } var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 800; this.canvas.height = 380; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.frameNo = 0; this.interval = setInterval(updateGameArea, 20); }, clear : function() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }, stop : function() { clearInterval(this.interval); } } function component(width, height, color, x, y, type) { if (type == "image") { this.image = new Image(); this.image.src = color; } this.type = type; this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.gravity = 0.05; this.gravitySpeed = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; if (type == "image") { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); } else if (this.type == "text") { ctx.font = this.width + " " + this.height; ctx.fillStyle = color; ctx.fillText(this.text, this.x, this.y); } } this.newPos = function() { this.gravitySpeed += this.gravity; this.x += this.speedX; this.y += this.speedY + this.gravitySpeed; this.hitBottom(); } this.hitBottom = function() { var rockbottom = myGameArea.canvas.height - this.height; if (this.y > rockbottom) { this.y = rockbottom; } } this.crashWith = function(otherobj) { var myleft = this.x; var myright = this.x + (this.width); var mytop = this.y; var mybottom = this.y + (this.height); var otherleft = otherobj.x; var otherright = otherobj.x + (otherobj.width); var othertop = otherobj.y; var otherbottom = otherobj.y + (otherobj.height); var crash = true; if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) { crash = false; } return crash; } } function updateGameArea() { var x, height, gap, minHeight, maxHeight, minGap, maxGap; for (i = 0; i < myObstacles.length; i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { myGameArea.stop(); return; } } myGameArea.clear(); myGameArea.frameNo += 1; if (myGameArea.frameNo == 1 || everyinterval(150)) { x = myGameArea.canvas.width; minHeight = 20; maxHeight = 200; height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight); minGap = 150; maxGap = 250; gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap); myObstacles.push(new component(15, height, "https://orig00.deviantart.net/bb11/f/2014/127/f/e/hexagon_wallpaper___version_3_by_designedby_jack-d7hh9xo.png", x, 0, "image")); myObstacles.push(new component(15, height, "https://orig00.deviantart.net/bb11/f/2014/127/f/e/hexagon_wallpaper___version_3_by_designedby_jack-d7hh9xo.png", x, height + gap, "image")); // Fixed game speed logic (was decreasing too fast before) gameSpeed -= 0.1; } myBackground.newPos(); myBackground.update(); for (i = 0; i < myObstacles.length; i += 1) { myObstacles[i].x += gameSpeed; myObstacles[i].update(); } myScore.text="Space Run SCORE: " + myGameArea.frameNo; myScore.update(); myGamePiece.newPos(); myGamePiece.update(); // Fixed your typo here } function accelerate(n) { myGamePiece.gravity = n; } // New Reset Game Function function resetGame() { // Stop the current game loop myGameArea.stop(); // Clear old obstacles myObstacles = []; // Reset game speed to initial value gameSpeed = 1; // Remove the old canvas to avoid duplicates document.body.removeChild(myGameArea.canvas); // Recreate canvas and start fresh game myGameArea.canvas = document.createElement("canvas"); startGame(); } function everyinterval(n) { if ((myGameArea.frameNo / n) % 1 == 0) {return true;} return false; } </script> </body> </html>
Key Changes I Made:
Added the Restart Button:
- Placed a new button right below your Accelerate button, linked to a
resetGame()function. Styled it with red text to stand out, but you can tweak this to match your game's vibe.
- Placed a new button right below your Accelerate button, linked to a
Built the
resetGame()Function:- Stops the active game loop to prevent leftover game logic from running in the background.
- Clears the obstacle array so old obstacles don't carry over to the new game.
- Resets the game speed back to its starting value of 1.
- Removes the old canvas element (so you don't end up with multiple canvases stacking on the page).
- Reinitializes the canvas and launches a fresh game session with
startGame().
Fixed Small Bugs:
- Corrected a typo in
updateGameArea()where you hadmyGamePiece.updinstead ofmyGamePiece.update(). - Adjusted the game speed decrease (you were dropping it by 1 every interval, which would quickly make obstacles move backward—now it decreases by 0.1 for a gradual difficulty ramp).
- Corrected a typo in
Now when you crash, just click the "Restart Game" button to jump back into action without needing to hit "Run Code" again!
内容的提问来源于stack exchange,提问作者Landon
相关产品推荐
相关产品推荐

