-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
79 lines (59 loc) · 2.06 KB
/
server.js
File metadata and controls
79 lines (59 loc) · 2.06 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
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var players = {};
var star = {
x: Math.floor(Math.random() * 700) + 50,
y: Math.floor(Math.random() * 500) + 50
};
var scores = {
blue: 0,
red: 0
};
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
console.log('a user connected');
players[socket.id] = {
rotation: 0,
x: Math.floor(Math.random() * 700) + 50,
y: Math.floor(Math.random() * 500) + 50,
playerId: socket.id,
team: (Math.floor(Math.random() * 2) == 0) ? 'red' : 'blue'
};
socket.emit('currentPlayers', players);
socket.broadcast.emit('newPlayer', players[socket.id]);
socket.on('disconnect', function () {
console.log('user disconnected');
delete players[socket.id];
io.emit('disconnect', socket.id);
});
// when a player moves, update the player data
socket.on('playerMovement', function (movementData) {
players[socket.id].x = movementData.x;
players[socket.id].y = movementData.y;
players[socket.id].rotation = movementData.rotation;
// emit a message to all players about the player that moved
socket.broadcast.emit('playerMoved', players[socket.id]);
});
// send the star object to the new player
socket.emit('starLocation', star);
socket.on('starCollected', function () {
if (players[socket.id].team === 'red') {
scores.red += 10;
} else {
scores.blue += 10;
}
star.x = Math.floor(Math.random() * 700) + 50;
star.y = Math.floor(Math.random() * 500) + 50;
io.emit('starLocation', star);
io.emit('scoreUpdate', scores);
});
socket.emit('scoreUpdate', scores);
});
// app.get('/', function (req, res) {
// res.sendFile(__dirname + '/index.html');
// });
server.listen(process.env.PORT || 8081, function () {
console.log(`Listening on ${server.address().port}`);
});