-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (44 loc) · 1.44 KB
/
server.js
File metadata and controls
55 lines (44 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 5000;
const Score = require('./models/Score');
const Score = require('./Score');
app.use(cors());
app.use(express.json());
// Connect to MongoDB (replace with your connection string)
mongoose.connect('mongodb://https://priyagangwar.github.io/Memory-Game/', { useNewUrlParser: true, useUnifiedTopology: true });
// Define routes here
app.listen(PORT, () => {
console.log(`Server is running at ${PORT}`);
});
// Save a new score
app.post('/api/scores', async (req, res) => {
try {
const newScore = new Score(req.body);
await newScore.save();
res.status(201).json(newScore);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// Get top 10 scores
app.get('/api/leaderboard', async (req, res) => {
try {
const topScores = await Score.find().sort({ score: -1 }).limit(10);
res.json(topScores);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
//Handling Game State (Server-Side)
//You might want to manage certain parts of the game state, like user scores or multiplayer interactions, on the server.
//In server.js
app.use(express.json());
let highScores = [];
app.post('/api/score', (req, res) => {
const { score } = req.body;
highScores.push(score);
res.json({ message: "Score saved!", highScores });
});