-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (65 loc) · 2.21 KB
/
server.js
File metadata and controls
73 lines (65 loc) · 2.21 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
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'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log('a user connected: ', socket.id);
// create a new player and add it to our players object
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'
};
// send the players object to the new player
socket.emit('currentPlayers', players);
// send the star object to the new player
socket.emit('starLocation', star);
// send the current scores
socket.emit('scoreUpdate', scores);
// update all other players of the new player
socket.broadcast.emit('newPlayer', players[socket.id]);
// when a player disconnects, remove them from our players object
socket.on('disconnect', function () {
console.log('user disconnected: ', socket.id);
delete players[socket.id];
// emit a message to all players to remove this player
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]);
});
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);
});
});
server.listen(8081, function () {
console.log(`Listening on ${server.address().port}`);
});