-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
99 lines (84 loc) · 2.59 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
var physics = require('./physics');
var sys = require('sys')
, url = require('url')
, http = require('http')
, io = require('socket.io')
, PORT = 8080 // MAKE SURE THIS IS SAME AS SOCKET.IO
, static = require('node-static')
// Create a node-static server to serve the current directory
, fileServer = new static.Server('./www', { cache: 7200, headers: {'X-Hello':'Starting static server!'} })
var httpServer = http.createServer(function (request, response) {
/* If we need multiple paths
var path = url.parse(request.url).pathname;
switch(path) {
case '/':
...
}); */
fileServer.serve(request, response, function (err, res) {
if (err) {
sys.error('> Error serving ' + request.url + ' - ' + err.message);
fileServer.serveFile('/404.html', err.headers, err.headers, request, response);
}
});
});
httpServer.listen(PORT);
console.log('> Server is listening on http://localhost:' + PORT);
/*****************************************************************/
// All the socket.io
var socket = io.listen(httpServer);
var clients = [];
var NUM_CLIENTS = 2;
// mapping of clients to entities held by that client
// Start a new game, giving the player role to the first one who joined
// Assumes NUM_CLIENTS clients
startGame = function() {
console.log('Starting the game with ' + NUM_CLIENTS + ' clients.');
clients[0].send({ playerId: 0, type: 'TheOne', position: [100, 300] });
for (var i = 1; i < clients.length; ++i) {
clients[i].send({ playerId: i, type: 'TestEnemy', position: [650, 300] });
}
for (var i = 0; i < clients.length; ++i) {
clients[i].playerId = i;
clients[i].entities = [];
}
var fps = 10;
setInterval(pushUpdates, 1000 / fps);
}
// Push updates to all clients
pushUpdates = function() {
var len = clients.length;
var entities = [];
for (var i = 0; i < len; ++i) {
for (var index in clients[i].entities) {
entities.push(clients[i].entities[index]);
}
}
physics.doDamage(entities);
for (var i = 0; i < len; ++i) {
clients[i].send({entities: entities});
}
}
socket.on('connection', function(client) {
if (clients.length >= NUM_CLIENTS) {
return;
}
clients.push(client);
if (clients.length === NUM_CLIENTS) {
startGame(this);
}
// Update list of entities for that client
client.on('message', function(message) {
if (clients[message.playerId] !== undefined) {
clients[message.playerId].entities = message.entities;
}
});
// Remove the client
client.on('disconnect', function() {
for (var i = 0; i < clients.length; ++i) {
if (this === clients[i]) {
console.log('Removing client #' + i);
clients.splice(i, 1);
}
}
});
});