-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
82 lines (62 loc) · 2.04 KB
/
server.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
var util = require ('util');
var io = require ('socket.io');
var Player = require("./Player").Player;
var socket;
var players;
function init () {
players = [];
socket = io.listen(7777);
socket.configure(function() {
socket.set("transports", ["websocket"]);
socket.set("log level", 2);
});
setEventHandlers();
}
var setEventHandlers = function() {
socket.sockets.on("connection", onSocketConnection);
};
function onSocketConnection(client) {
util.log("New player has connected: "+client.id);
client.on("disconnect", onClientDisconnect);
client.on("new player", onNewPlayer);
client.on("move player", onMovePlayer);
}
function onClientDisconnect() {
util.log("Player has disconnected: "+this.id);
var playerToRemove = playerById(this.id);
if (!playerToRemove) {
util.log("Player not found");
return;
}
players.splice(players.indexOf(playerToRemove), 1);
this.broadcast.emit("remove player", {id: this.id});
}
function onNewPlayer(data) {
var newPlayer = new Player (data.x, data.y);
newPlayer.id = this.id;
this.broadcast.emit("new player", {id: newPlayer.id, x: newPlayer.getX(), y: newPlayer.getY()});
this.emit("getMyId", {id: this.id});
for (var i = 0; i < players.length; i++) {
var existingPlayer = players[i];
this.emit("new player", {id: existingPlayer.id, x: existingPlayer.getX(), y: existingPlayer.getY()});
};
players.push(newPlayer);
};
function onMovePlayer(data) {
var playerToMove = playerById (data.id);
if (!playerToMove) {
util.log("Player not found");
return;
}
playerToMove.x = data.x;
playerToMove.y = data.y;
playerToMove.angle = data.angle;
this.broadcast.emit("move player", {id: playerToMove.id, x: playerToMove.x, y: playerToMove.y, angle: playerToMove.angle});
};
function playerById (id) {
for (var i = 0; i < players.length; ++ i) {
if (players[i].id === id) return players[i];
}
return false;
}
init ();