-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
155 lines (133 loc) · 4.26 KB
/
Copy pathserver.js
File metadata and controls
155 lines (133 loc) · 4.26 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/* ============================================================
MapVexa — Custom Server (Next.js + Socket.io)
Runs Next.js alongside a WebSocket server for multiplayer.
============================================================ */
const { createServer } = require('node:http');
const next = require('next');
const { Server } = require('socket.io');
const Database = require('better-sqlite3');
const fs = require('fs');
const path = require('path');
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = process.env.PORT || 3000;
// Initialize Next.js
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
// Initialize Database
const db = new Database('mapvexa.db');
db.pragma('journal_mode = WAL');
// Simple schema setup
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL,
passwordHash TEXT,
xp INTEGER DEFAULT 0,
level INTEGER DEFAULT 1,
streak INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS friends (
user_id TEXT,
friend_id TEXT,
status TEXT DEFAULT 'pending',
PRIMARY KEY (user_id, friend_id)
);
CREATE TABLE IF NOT EXISTS curated_locations (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
countryCode TEXT NOT NULL,
countryName TEXT NOT NULL,
lat REAL NOT NULL,
lon REAL NOT NULL,
imageUrl TEXT NOT NULL
);
`);
// Seed curated locations if empty
const locCount = db.prepare('SELECT COUNT(*) as count FROM curated_locations').get().count;
if (locCount === 0) {
try {
const locationsPath = path.join(__dirname, 'public', 'curated_locations.json');
const locationsData = JSON.parse(fs.readFileSync(locationsPath, 'utf-8'));
const insertLoc = db.prepare(`
INSERT INTO curated_locations (id, name, countryCode, countryName, lat, lon, imageUrl)
VALUES (@id, @name, @countryCode, @countryName, @lat, @lon, @imageUrl)
`);
const insertMany = db.transaction((locations) => {
for (const loc of locations) {
insertLoc.run(loc);
}
});
insertMany(locationsData);
console.log(`[DB] Seeded ${locationsData.length} curated locations into the database.`);
} catch (err) {
console.error('[DB] Failed to seed curated locations:', err.message);
}
}
app.prepare().then(() => {
const httpServer = createServer(handler);
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// Multiplayer State
const rooms = new Map();
io.on('connection', (socket) => {
console.log(`[Socket] User connected: ${socket.id}`);
// Join a room
socket.on('join-room', (roomId, user) => {
socket.join(roomId);
console.log(`[Socket] User ${user?.username} joined room ${roomId}`);
if (!rooms.has(roomId)) {
rooms.set(roomId, {
id: roomId,
players: [],
state: 'waiting',
gameMode: 'capital-challenge',
round: 1
});
}
const room = rooms.get(roomId);
if (!room.players.find(p => p.id === (user?.id || socket.id))) {
room.players.push({
id: user?.id || socket.id,
socketId: socket.id,
username: user?.username || 'Guest',
score: 0,
ready: false
});
}
io.to(roomId).emit('room-update', room);
});
// Chat messages
socket.on('send-chat', (roomId, message) => {
io.to(roomId).emit('chat-message', message);
});
socket.on('disconnect', () => {
console.log(`[Socket] User disconnected: ${socket.id}`);
// Simple cleanup for MVP
for (const [roomId, room] of rooms.entries()) {
const playerIndex = room.players.findIndex(p => p.socketId === socket.id);
if (playerIndex !== -1) {
room.players.splice(playerIndex, 1);
if (room.players.length === 0) {
rooms.delete(roomId);
} else {
io.to(roomId).emit('room-update', room);
}
}
}
});
});
httpServer
.once('error', (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});