-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
116 lines (96 loc) · 2.52 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
var express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
User = require("./js/server/User.js"),
Game = require("./js/server/Game.js"),
nsp = io.of("/apollo/"),
gameLoop,
local = true; //change this value if not on server - i.e. localhost
;
var idCounter = 0;
var users = [];
var game = new Game();
app.use(express.static(__dirname + "/"));
app.get('/', function(request, response){
response.sendFile(__dirname + "/graphics.html");
});
http.listen("443", function(){
console.log("server started on port 443");
});
if (local)
io.on("connection", connection);
else
nsp.on("connection", connection);
function connection(socket){
var user = new User(socket, ++idCounter);
var playerData = game.playerConnected(user);
var data = {
id: user.id,
users: [],
model: playerData.model
};
for (var i = 0; i < users.length; i++){
data.users.push(game.getPlayerData(users[i].id));
}
socket.emit("connection info", data);
socket.broadcast.emit("new user", { id: user.id, playerData: playerData });
users.push(user);
socket.on("disconnect", function(){
userDisconnected(user);
});
socket.on("game update", gameUpdate);
socket.on("chat message", handleChat);
startGame();
};
function userDisconnected(user){
var id = user.id;
game.playerDisconnected(user.id);
for (var i = 0; i < users.length; i++){
if (users[i] == user){
users.splice(i, 1);
i--;
break;
}
}
if (users.length === 0){
stopGame();
}
sendMessage("user disconnected", { id: id });
};
function startGame(){
if (!game.running){
console.log("game started");
game.start();
gameLoop = setInterval(updateClients, 30);
sendMessage("game started");
}
};
function stopGame(){
console.log("game stopped");
game.running = false;
clearInterval(gameLoop);
idCounter = 0;
}
function updateClients(){
var gameData = game.sendUpdate();
sendMessage("game update", gameData);
};
function handleChat(data){
sendMessage("chat message", {
text: data.text,
name: data.id,
timestamp: Date.now()
});
}
function gameUpdate(data){
game.receiveUpdate(data);
};
function sendMessage(message, data){
if (local){
io.emit(message, data);
}
else{
nsp.emit(message, data);
}
}