-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
84 lines (68 loc) · 2.16 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
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const engine = require('./engine.js');
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
function gameLoop() {
Object.keys(engine.players).forEach((playerId) => {
let player = engine.players[playerId];
if(engine.checkCollisionWithStar(player)){
player.score++;
engine.generateStar();
}
engine.movePlayer(playerId, player.velX, player.velY);
});
let playersSorted = {};
Object.keys(engine.players)
.sort((player1, player2) => engine.players[player1].score > engine.players[player2].score)
.forEach(playerId => playersSorted[playerId] = engine.players[playerId]);
io.emit('gameStateUpdate', {players: playersSorted, star: engine.star});
}
io.on('connection', (socket) => {
console.log('User connected: ', socket.id);
engine.players[socket.id] = {
name: engine.nameOfPlayer(),
score: 0,
x: 0,
y: 0,
velX: 0,
velY: 0,
height: 20,
width: 20,
colour: engine.stringToColour(socket.id),
position: 'up'
};
socket.on('disconnect', () => {
delete engine.players[socket.id];
io.emit('gameStateUpdate', engine.players);
});
socket.on('up', () => {
console.log('up message received from ', socket.id);
engine.players[socket.id].position = 'up';
engine.accelPlayer(socket.id, 0, -1);
});
socket.on('down', () => {
console.log('down message received from ', socket.id);
engine.players[socket.id].position = 'down';
engine.accelPlayer(socket.id, 0, 1);
});
socket.on('left', () => {
console.log('left message received from ', socket.id);
engine.players[socket.id].position = 'left';
engine.accelPlayer(socket.id, -1, 0);
});
socket.on('right', () => {
console.log('right message received from ', socket.id);
engine.players[socket.id].position = 'right';
engine.accelPlayer(socket.id, 1, 0);
})
});
http.listen(process.env.PORT || 3000, () => {
console.log('Server listening');
engine.generateStar();
setInterval(gameLoop, 30);
});