-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsocket.js
More file actions
55 lines (47 loc) · 1.75 KB
/
socket.js
File metadata and controls
55 lines (47 loc) · 1.75 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
'use strict';
let io = null;
const mongoose = require('mongoose');
const Game = mongoose.model('Game');
const User = mongoose.model('User');
module.exports = {
init: function(http) {
io = new require('socket.io').listen(http);
// api key authorization
io.use(function(socket, next) {
if(!socket.request._query || !socket.request._query.api_key) {
next(new Error('No api_key sent in query'));
} else {
User.findOne({'api_key': socket.request._query.api_key}, function(err, user) {
if(!user) {
next(new Error('No user found with api_key'));
} else {
socket.join(user._id);
next();
}
});
}
});
},
sendStateChange: function(game) {
io.to(game.player1).emit('statechange', game.outputForUser(game.player1));
if(game.player2) {
io.to(game.player2).emit('statechange', game.outputForUser(game.player2));
}
},
sendMove: function(game, move) {
const data = {
game_id: game._id,
move: move
};
io.to(game.player1).emit('move', data);
if(game.player2) {
// Give rotated perspective
const rotatedData = JSON.parse(JSON.stringify(data));
rotatedData.move.square.row = 9 - data.move.square.row;
rotatedData.move.square.column = 9 - data.move.square.column;
rotatedData.move.square_to.row = 9 - data.move.square_to.row;
rotatedData.move.square_to.column = 9 - data.move.square_to.column;
io.to(game.player2).emit('move', rotatedData);
}
}
}