-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
102 lines (89 loc) · 2.37 KB
/
server.js
File metadata and controls
102 lines (89 loc) · 2.37 KB
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
const express = require('express');
const app = express();
var expressWs = require('express-ws')(app);
app.use(express.static('.'));
function Drawable(clientId, topLeftX, topLeftY, width, height, color, speed, direction){
this.clientId = clientId;
this.topLeftX = topLeftX;
this.topLeftY = topLeftY;
this.width = width;
this.height = height;
this.color = color;
this.speed = speed;
this.direction = direction;
};
let clients = [];
let drawables = [];
let clientCounter = 0;
const canvas = {width:600,height:300};
app.ws('/echo', function(ws, req){
const clientId = clientCounter;
clients.push({clientId:clientId,connection:ws});
clientCounter++;
const topLeftX = Math.random()*(canvas.width-30);
const topLeftY = Math.random()*(canvas.height-30);
const color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
let drawable = new Drawable(clientId, topLeftX, topLeftY, 10, 10, color, 1, null);
drawables.push(drawable);
ws.on('message', function(msg){
const message = JSON.parse(msg);
switch(message.type){
case 'userAction':
switch(message.data){
case 'ArrowUp':
drawable.direction = 'up';
break;
case 'ArrowDown':
drawable.direction = 'down';
break;
case 'ArrowRight':
drawable.direction = 'right';
break;
case 'ArrowLeft':
drawable.direction = 'left';
break;
}
break;
}
});
ws.on('error',function(){clear(clientId)});
ws.on('close',function(){clear(clientId)});
});
function clear(clientId){
clients = clients.filter(function(client){
if (client.clientId != clientId){
return client;
}
});
drawables = drawables.filter(function(drawable){
if (drawable.clientId != clientId){
return drawable;
}
});
}
let interval = setInterval(function(){
drawables.forEach(function(drawable){
switch(drawable.direction){
case 'right':
drawable.topLeftX+=drawable.speed;
break;
case 'left':
drawable.topLeftX-=drawable.speed;
break;
case 'up':
drawable.topLeftY-=drawable.speed;
break;
case 'down':
drawable.topLeftY+=drawable.speed;
break;
default:
break;
}
});
clients.forEach(function(client){
if (client.connection.readyState == 1){
client.connection.send(JSON.stringify({type:'model',data:drawables}));
}
});
},40);
app.listen(3000);