-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
95 lines (68 loc) · 2.08 KB
/
index.js
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
// Import required modules
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
// Import custom modules
const Game = require('./assets/game')
const Player = require('./assets/player')
// Initialize an Express application
const app = express();
// Create an HTTP server using the Express app
const server = http.createServer(app);
// Initialize a new instance of Socket.IO with the HTTP server
const io = new Server(server);
// Serve static files from the 'public' directory
app.use(express.static('public'));
// Set the port for the server
const port = 3000;
// Start the server and listen on the specified port
server.listen(port, () => {
console.clear();
console.log(`Server is running on port ${port}`);
});
// Game object
let games = []
// Handle admin connections
io.of('/host').on('connection', (socket) => {
games.push(
new Game(socket)
)
// socket.emit('update', game)
socket.on('start', () => {
game.active = true
socket.emit('start', game)
io.of('/client').emit('start')
})
socket.on('disconnect', () => {
if (games) {
games = games.filter(game => game.id !== socket.id);
}
})
})
// Handle client connections
io.of('/client').on('connection', (socket) => {
socket.on('join', (name) => {
if (game.host) {
if (!game.active) {
let client = new Player(
name,
socket.id
)
game.clients.push(client)
socket.emit('join')
} else {
socket.emit('reject', `Sorry ${name}, the game has already started!`)
}
} else {
socket.emit('reject', `Sorry ${name}, waiting for someone to host the game!`)
}
})
socket.emit('update', (game) => {
})
socket.on('disconnect', () => {
if (game.clients) {
game.clients = game.clients.filter(client => client.id !== socket.id);
}
io.of('/admin').emit('update', game);
})
})