-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathio.js
More file actions
75 lines (63 loc) · 2.06 KB
/
io.js
File metadata and controls
75 lines (63 loc) · 2.06 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
const Game = require('./models/game');
const board = require('./config/game');
// const gameService = require( './src/utils/gameService');
let io;
var games = {};
module.exports = {
init: function(httpServer) {
io = require('socket.io')(httpServer);
io.on('connection', function(socket) {
socket.on('chat', function(chat) {
io.emit('chat', chat);
});
socket.on('getActiveGame', function(userId) {
var game = Object.values(games).find(g => g.players.some(p => p.id === userId));
if (game) {
socket.gameId = game._id;
socket.join(game._id);
}
io.emit('gameData', game);
});
socket.on('createGame', function(user) {
var game = new Game();
board.createPlayer(game, user);
game.save(function(err) {
socket.gameId = game.id;
socket.join(game.id);
io.to(game.id).emit('gameData', game);
games[game._id] = game;
});
});
socket.on('joinGame', function(user, roomId) {
var game = games[roomId];
board.createPlayer(game, user);
socket.gameId = game.id;
socket.join(roomId);
if (game.players.length === 4) game.gameInPlay = true;
io.to(game.id).emit('gameData', game);
game.save();
});
socket.on('startGame', function() {
var game = games[socket.gameId];
game.gameInPlay = true;
io.to(game.id).emit('gameData', game);
game.save();
});
socket.on('rollDice', function() {
var game = games[socket.gameId];
var randomNumber = Math.floor(Math.random() * 6) + 1;
game.dice = randomNumber;
board.checkIfMoveAvailable(game);
io.to(game.id).emit('gameData', game);
game.save();
});
socket.on('movePiece', function(piece) {
var game = games[socket.gameId];
board.movePiece(game, piece);
io.to(game.id).emit('gameData', game);
game.save();
});
})
},
getIo: function() {return io}
};