如何通过Ajax将游戏得分写入文本文件并实现高分榜与保存提示
Hey there! Let's break this down step by step since you're new to Ajax—no confusing jargon, just straightforward explanations and code you can drop right in. 😊
First, a quick key point: Frontend JavaScript (like your Phaser game) can't directly write to text files on a server. We need a backend script (I'll use PHP since it's easy to set up for beginners) to handle the file writing, and Ajax is the "messenger" that sends your score from the game to the backend.
Let's modify your hitPipe function (the one that triggers when the bird hits a pipe) to send the score and handle the success message. Here's the full code:
hitPipe: function() { // First, handle game-over state (pause physics, hide bird, etc.) this.game.physics.arcade.isPaused = true; this.bird.visible = false; // Grab the current score const finalScore = this.score; // Create an Ajax request object const xhr = new XMLHttpRequest(); // Configure the request: POST method, point to our backend script, async = true (so game doesn't freeze) xhr.open('POST', 'save-score.php', true); // Tell the backend we're sending form-style data xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Listen for when the request finishes xhr.onreadystatechange = function() { // Check if request is complete and successful if (xhr.readyState === 4 && xhr.status === 200) { // Show the success alert alert("your score has been saved successfully"); // Now load and display the high scores loadHighScores(); } else if (xhr.readyState === 4) { // If something went wrong alert("Oops, we couldn't save your score. Try again!"); } }; // Send the score to the backend (format: key=value) xhr.send(`score=${finalScore}`); }
What's happening here?
XMLHttpRequestis the core Ajax tool—it lets the game talk to the backend without reloading the page.open()sets up the request:POSTis used for sending data,save-score.phpis our backend script (we'll write this next), andtruekeeps the game responsive while the request runs.onreadystatechangewatches for when the backend sends a response. When it's done (readyState === 4) and successful (status === 200), we show the alert and load the high scores.
Add these functions to your game code to fetch and show the high scores after saving:
// Fetch high scores from the backend function loadHighScores() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'get-highscores.php', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // Parse the JSON response from the backend const highScores = JSON.parse(xhr.responseText); // Display the scores in the game displayHighScores(highScores); } }; xhr.send(); } // Render high scores on the game screen function displayHighScores(scores) { // Clear any existing high score text (if replaying) if (window.highScoreDisplay) { window.highScoreDisplay.destroy(); } // Create a title for the high scores window.highScoreDisplay = game.add.text( game.world.centerX, 100, "High Scores", { font: "40px Arial", fill: "#ffd700" } ); window.highScoreDisplay.anchor.setTo(0.5); // Center the text // List each score scores.forEach((score, index) => { const yPosition = 160 + (index * 40); const scoreText = game.add.text( game.world.centerX, yPosition, `${index + 1}. ${score}`, { font: "30px Arial", fill: "#ffffff" } ); scoreText.anchor.setTo(0.5); }); }
You'll need two simple PHP files in the same folder as your game HTML. These handle saving the score and returning sorted high scores.
save-score.php (Saves the score to a text file)
<?php // Allow cross-origin requests (only needed if your game is on a different domain; comment out for local testing) // header("Access-Control-Allow-Origin: *"); // Get the score sent from the game $score = $_POST['score'] ?? null; // Validate the score is a number if ($score !== null && is_numeric($score)) { // Open (or create) the highscores.txt file in append mode $file = fopen('highscores.txt', 'a'); // Write the score on a new line fwrite($file, $score . "\n"); fclose($file); // Send a success response echo "success"; } else { // Send an error response if the score is invalid http_response_code(400); echo "Invalid score"; } ?>
get-highscores.php (Reads and returns sorted high scores)
<?php // Allow cross-origin requests (same note as above) // header("Access-Control-Allow-Origin: *"); $scores = []; // Check if the highscores file exists if (file_exists('highscores.txt')) { // Read all lines from the file (ignore empty lines) $lines = file('highscores.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // Convert string scores to numbers $scores = array_map('intval', $lines); // Sort scores from highest to lowest rsort($scores); // Keep only the top 10 scores (adjust this number if you want more/less) $scores = array_slice($scores, 0, 10); } // Send the scores as JSON (easy for the game to parse) header('Content-Type: application/json'); echo json_encode($scores); ?>
- File Permissions: Make sure your server has write access to the folder where
highscores.txtwill be created. For local testing (like with XAMPP/WAMP), this is usually already set up. For live servers, you might need to set the folder permissions to755or777. - Local Testing: If you're opening your game as a local HTML file (
file://), you'll run into cross-domain issues. Instead, put your game files in your server's root folder (likehtdocsfor XAMPP) and access it viahttp://localhost/your-game-folder/. - Data Safety: This is a simple setup for learning. For a real game, you'd want to add user authentication (so players can't fake scores) and use a database instead of a text file (more reliable for large numbers of scores).
- Player plays the game,
this.scoreincreases. - Bird hits a pipe →
hitPiperuns, game pauses. - Ajax sends
this.scoretosave-score.php. - Backend writes the score to
highscores.txt. - Success alert pops up in the game.
- Ajax fetches sorted scores from
get-highscores.php. - High scores are displayed on the game screen.
内容的提问来源于stack exchange,提问作者Maurice

