如何实现Phaser 3游戏分数与MySQL数据库的交互
Got it, let's break this down step by step. Since your Phaser game runs in the browser, module.exports won't work for sending data to a backend—we'll use HTTP requests instead. We'll cover three key parts: updating your frontend to send the final score, building a simple backend to handle MySQL operations, and fetching the high score to display in your game.
1. Frontend: Send Final Score to Backend
First, replace the module.exports line in your game code with a function that sends the score, username, and timestamp to your backend API using fetch. Update the update function where you handle game over:
function update() { if (gameOver) { var timeStamp = Math.floor(Date.now()) / 1000; var userName = prompt("Please enter your name", "name"); finalScore = score; // Send data to backend API fetch('/api/save-score', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ userName: userName, score: finalScore, date: new Date(timeStamp * 1000) // Convert timestamp to valid Date for MySQL }) }) .then(response => response.json()) .then(data => { console.log('Score saved successfully:', data); }) .catch(error => { console.error('Error saving score:', error); }); console.log("User: " + userName + "'s score is " + finalScore + " at " + timeStamp + "."); gameOver = false; // Optional: Restart game if user confirms if (window.confirm("Would you like to play again?")) { window.location.reload(); // Simple restart; you could also use Phaser's scene restart method } } // ... rest of your existing update code remains unchanged }
2. Backend: Handle MySQL Operations (Node.js/Express)
You'll need a simple Node.js backend to connect to MySQL, save the score, and return the high score. First, install required dependencies:
npm install express mysql2 cors
Create a file named server.js with this code:
const express = require('express'); const mysql = require('mysql2'); const cors = require('cors'); const app = express(); const port = 3000; // Configure MySQL connection (replace with your actual credentials) const db = mysql.createConnection({ host: 'your-mysql-host', // e.g., 'localhost' user: 'your-mysql-user', // e.g., 'root' password: 'your-mysql-password', database: 'your-database-name' }); // Connect to MySQL db.connect((err) => { if (err) throw err; console.log('Connected to MySQL database!'); }); app.use(cors()); app.use(express.json()); // API endpoint to save user score app.post('/api/save-score', (req, res) => { const { userName, score, date } = req.body; const query = 'INSERT INTO highScores (userName, score, date) VALUES (?, ?, ?)'; db.query(query, [userName, score, date], (err, result) => { if (err) { res.status(500).json({ error: err.message }); return; } res.json({ success: true, scoreId: result.insertId }); }); }); // API endpoint to get all-time high score app.get('/api/get-highscore', (req, res) => { const query = 'SELECT userName, score FROM highScores ORDER BY score DESC LIMIT 1'; db.query(query, (err, results) => { if (err) { res.status(500).json({ error: err.message }); return; } if (results.length === 0) { res.json({ userName: 'No scores yet', score: 0 }); return; } res.json(results[0]); }); }); // Optional: Add endpoint for monthly high score app.get('/api/get-monthly-highscore', (req, res) => { const query = ` SELECT userName, score FROM highScores WHERE DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ORDER BY score DESC LIMIT 1 `; db.query(query, (err, results) => { if (err) { res.status(500).json({ error: err.message }); return; } res.json(results.length ? results[0] : { userName: 'No monthly scores', score: 0 }); }); }); app.listen(port, () => { console.log(`Backend running on http://localhost:${port}`); });
3. Frontend: Import and Display High Score
Add code to fetch the high score when your game starts (in the create function) and display it alongside the current score:
function create() { // ... your existing create code (background, platforms, player, etc.) ... // Fetch and display all-time high score let highScoreText; fetch('/api/get-highscore') .then(response => response.json()) .then(data => { highScoreText = this.add.text(16, 50, `High Score: ${data.score} by ${data.userName}`, { fontSize: '24px', fill: '#000' }); }) .catch(error => { console.error('Error fetching high score:', error); highScoreText = this.add.text(16, 50, 'High Score: Unavailable', { fontSize: '24px', fill: '#000' }); }); // ... rest of your existing create code (colliders, overlaps, etc.) ... }
Important Setup Steps
- Create MySQL Table: Run this SQL query in your database to create the
highScorestable:CREATE TABLE highScores ( id INT AUTO_INCREMENT PRIMARY KEY, userName VARCHAR(50) NOT NULL, score INT NOT NULL, date DATETIME NOT NULL ); - Start Backend: Run
node server.jsin your terminal before launching your Phaser game. - Update Credentials: Replace the placeholder MySQL connection details in
server.jswith your actual database credentials.
内容的提问来源于stack exchange,提问作者CasaCoding

