-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmorpion.js
99 lines (73 loc) · 2.64 KB
/
morpion.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
96
97
98
99
const sessionController = require('./sessionController');
const { checkAuthenticated } = require('./auth');
let rooms = [];
function init(app, socketio) {
socketio.use(sessionController.wrap(sessionController.sessionMiddleware));
app.get('/morpion', checkAuthenticated, (req, res) => {
res.render('morpion/morpion', { username: req.user.username });
});
socketio.on("connect_error", (err) => {
console.log(`[MORPION] connect_error due to ${err.message}`);
});
socketio.on('connection', (socket) => {
console.log(`[MORPION] connection ${socket.id}`);
socket.on('playerData', (player) => {
console.log(`[MORPION] playerData ${player.username}`);
let room;
if (!player.roomId) {
room = createRoom(player);
console.log(`[MORPION] create room - ${room.id} - ${player.username}`);
} else {
room = rooms.find(r => r.id === player.roomId);
if (room === undefined) {
return;
}
player.roomId = room.id;
room.players.push(player);
}
socket.join(room.id);
socketio.to(socket.id).emit('join room', room.id);
if (room.players.length === 2) {
socketio.to(room.id).emit('start game', room.players);
}
});
socket.on('get rooms', () => {
socketio.to(socket.id).emit('list rooms', rooms);
});
socket.on('play', (player) => {
console.log(`[play] ${player.username}`);
socketio.to(player.roomId).emit('play', player);
});
socket.on('play again', (roomId) => {
const room = rooms.find(r => r.id === roomId);
if (room && room.players.length === 2) {
socketio.to(room.id).emit('play again', room.players);
}
})
socket.on('disconnect', () => {
console.log(`[MORPION] disconnect ${socket.id}`);
let room = null;
rooms.forEach(r => {
r.players.forEach(p => {
if (p.socketId === socket.id && p.host) {
room = r;
rooms = rooms.filter(r => r !== room);
}
})
})
});
});
}
function createRoom(player) {
const room = { id: roomId(), players: [] };
player.roomId = room.id;
room.players.push(player);
rooms.push(room);
return room;
}
function roomId() {
return Math.random().toString(36).substring(2, 2 + 9);
}
module.exports = {
init: init
}