-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.js
95 lines (83 loc) · 2.49 KB
/
Environment.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
var games = {};
var Environment = function(_socket) {
var socket = _socket;
this.handleError = function(message) {
console.log('ERROR', message);
socket.emit('error', message);
};
this.withPlayer = function(callback) {
var _this = this;
socket.get('player', function (err, player) {
if (err || !player)
return _this.handleError('You\'re not logged in.');
callback(player);
});
};
this.broadcastGameRoom = function(game, playerField) {
if (playerField !== null)
this.refreshGame(socket.broadcast.to(game.getName()), game, playerField);
};
this.refreshGame = function(receiver, game, playerField) {
receiver.emit('refresh game', this.getGameData(game, playerField));
};
this.getGameData = function(game, playerField) {
var opponent = game.getOpponent(playerField);
return {
active: game.isActive(playerField),
gameOver: game.isGameOver(),
name: game.getName(),
own: {
name: playerField.getName(),
field: playerField.getField().get(),
ready: playerField.isReady(),
won: playerField.getPlayer().gamesWon,
lost: playerField.getPlayer().gamesLost
},
opponent: opponent ? {
name: opponent.getName(),
field: opponent.getField().filterShot(),
ready: opponent.isReady(),
won: opponent.getPlayer().gamesWon,
lost: opponent.getPlayer().gamesLost
} : null
};
};
this.getGame = function(gameName) {
if (!games[gameName]) {
this.handleError('Game with name <' + gameName + '> not found.');
return null;
}
return games[gameName];
};
this.listGames = function(receiver) {
var gameList = [];
Object.keys(games).forEach(function (name) {
var opponent = games[name].getVisitor();
var creator = games[name].getCreator();
gameList.push({
name: name,
creator: {
name: creator.getName(),
won: creator.getPlayer().gamesWon,
lost: creator.getPlayer().gamesLost
},
opponent: opponent ? {
name: opponent.getName(),
won: opponent.getPlayer().gamesWon,
lost: opponent.getPlayer().gamesLost
} : null
});
});
receiver.emit('list games', gameList);
}
this.getGame = function(name) {
return games[name];
}
this.addGame = function(game) {
games[game.getName()] = game;
}
this.removeGame = function(game) {
delete games[game.getName()];
}
};
module.exports = Environment;