-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
128 lines (103 loc) · 2.41 KB
/
app.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
117
118
119
120
121
122
123
124
125
126
127
128
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var ProtoBuf = require("./node_modules/protobufjs");
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
var SOCKET_LIST = {};
var PLAYER_LIST = {};
var Entity = function(id){
var self = {
x:250,
y:250,
spdX:0,
spdY:1,
id:id,
number:""+Math.floor(10 * Math.random()),
};
self.update = function() {
self.updatePosition();
};
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
};
return self;
}
var Player = function(id) {
var self = Entity();
self.id = id;
self.pressingLeft = false;
self.pressingRight = false;
self.pressingUp = false;
self.pressingDown = false;
self.maxSpeed = 10;
self.updatePosition = function(){
if(self.pressingRight)
self.x += self.maxSpd;
if(self.pressingLeft)
self.x -= self.maxSpd;
if(self.pressingUp)
self.y -= self.maxSpd;
if(self.pressingDown)
self.y += self.maxSpd;
}
return self;
}
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket) {
console.log("socket connection");
socket.emit('hello',"hello");
socket.id = Math.random();
var player = Player(socket.id);
PLAYER_LIST[socket.id] = player;
SOCKET_LIST[socket.id ] = socket;
socket.on('disconnect', function(){
delete PLAYER_LIST[socket.id];
delete SOCKET_LIST[socket.id];
});
socket.on('keyPress', function(data) {
if(data.inputId == 'left')
{
player.pressingLeft = data.state;
}
else if(data.inputId == 'right')
{
player.pressingRight = data.state;
}
else if(data.inputId == 'up')
{
player.pressingUp = data.state;
}
else if(data.inputId == 'down')
{
player.pressingDown = data.state;
}
});
//socket.on('happy', function(data) {
// console.log('happy because' + data.reason);
//});
//socket.emit('serverMsg', {
// msg:'hello',
//});
});
setInterval(function() {
var pack = [];
for( var i in PLAYER_LIST) {
var player = PLAYER_LIST[i];
player.updatePosition();
pack.push({
x:player.x,
y:player.y,
number:player.number
});
}
for( var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('newPosition', pack);
}
}, 1000/25);