-
Notifications
You must be signed in to change notification settings - Fork 109
/
server.js
59 lines (48 loc) · 1.58 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
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
app.use('/css',express.static(__dirname + '/css'));
app.use('/js',express.static(__dirname + '/js'));
app.use('/assets',express.static(__dirname + '/assets'));
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
});
server.lastPlayderID = 0;
server.listen(process.env.PORT || 8081,function(){
console.log('Listening on '+server.address().port);
});
io.on('connection',function(socket){
socket.on('newplayer',function(){
socket.player = {
id: server.lastPlayderID++,
x: randomInt(100,400),
y: randomInt(100,400)
};
socket.emit('allplayers',getAllPlayers());
socket.broadcast.emit('newplayer',socket.player);
socket.on('click',function(data){
console.log('click to '+data.x+', '+data.y);
socket.player.x = data.x;
socket.player.y = data.y;
io.emit('move',socket.player);
});
socket.on('disconnect',function(){
io.emit('remove',socket.player.id);
});
});
socket.on('test',function(){
console.log('test received');
});
});
function getAllPlayers(){
var players = [];
Object.keys(io.sockets.connected).forEach(function(socketID){
var player = io.sockets.connected[socketID].player;
if(player) players.push(player);
});
return players;
}
function randomInt (low, high) {
return Math.floor(Math.random() * (high - low) + low);
}