-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
161 lines (129 loc) · 4.17 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const expect = require('chai');
const socket = require('socket.io');
const helmet = require('helmet');
const cors = require('cors');
const nocache = require("nocache");
const fccTestingRoutes = require('./routes/fcctesting.js');
const runner = require('./test-runner.js');
const app = express();
app.use(
helmet({
noSniff: true,
xssFilter: true,
hidePoweredBy: {
setTo: "PHP 7.4.3",
}
})
);
app.use(nocache());
app.use(cors({ origin: '*' })); //For FCC testing purposes only
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/assets', express.static(process.cwd() + '/assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Index page (static HTML)
app.route('/')
.get(function (req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
//For FCC testing purposes
fccTestingRoutes(app);
// 404 Not Found Middleware
app.use(function(req, res, next) {
res.status(404)
.type('text')
.send('Not Found');
});
const portNum = process.env.PORT || 3000;
// Set up server and tests
const server = app.listen(portNum, () => {
console.log(`Listening on port ${portNum}`);
if (process.env.NODE_ENV==='test') {
console.log('Running Tests...');
setTimeout(function () {
try {
runner.run();
} catch (error) {
console.log('Tests are not valid:');
console.error(error);
}
}, 1500);
}
});
// Socket.io setup:
// Start app and bind
// Socket.io to the same port
const io = socket(server);
const Collectible = require('./public/Collectible');
const { generateStartPos, canvasCalcs } = require('./public/canvas-data');
let currPlayers = [];
const destroyedMedals = [];
const generateMedal = () => {
const rand = Math.random();
let medalValue;
if (rand < 0.6) {
medalValue = 1;
} else if (rand < 0.85) {
medalValue = 2;
} else {
medalValue = 3;
}
return new Collectible({
x: generateStartPos(canvasCalcs.playFieldMinX, canvasCalcs.playFieldMaxX, 5),
y: generateStartPos(canvasCalcs.playFieldMinY, canvasCalcs.playFieldMaxY, 5),
value: medalValue,
id: Date.now()
});
}
let medal = generateMedal();
io.sockets.on('connection', socket => {
console.log(`New connection ${socket.id}`);
socket.emit('init', { id: socket.id, players: currPlayers, medal });
socket.on('new-player', obj => {
obj.id = socket.id;
currPlayers.push(obj);
socket.broadcast.emit('new-player', obj);
});
socket.on('move-player', (dir, obj) => {
const movingPlayer = currPlayers.find(player => player.id === socket.id);
if (movingPlayer) {
movingPlayer.x = obj.x;
movingPlayer.y = obj.y;
socket.broadcast.emit('move-player', { id: socket.id, dir, posObj: { x: movingPlayer.x, y: movingPlayer.y } });
}
});
socket.on('stop-player', (dir, obj) => {
const stoppingPlayer = currPlayers.find(player => player.id === socket.id);
if (stoppingPlayer) {
stoppingPlayer.x = obj.x;
stoppingPlayer.y = obj.y;
socket.broadcast.emit('stop-player', { id: socket.id, dir, posObj: { x: stoppingPlayer.x, y: stoppingPlayer.y } });
}
});
socket.on('destroy-item', ({ playerId, medalValue, medalId }) => {
if (!destroyedMedals.includes(medalId)) {
const scoringPlayer = currPlayers.find(obj => obj.id === playerId);
const sock = io.sockets.connected[scoringPlayer.id];
scoringPlayer.score += medalValue;
destroyedMedals.push(medalId);
// Broadcast to all players when someone scores
io.emit('update-player', scoringPlayer);
// Communicate win state and broadcast losses
if (scoringPlayer.score >= 100) {
sock.emit('end-game', 'win');
sock.broadcast.emit('end-game', 'lose');
}
// Generate new medal and send it to all players
medal = generateMedal();
io.emit('new-medal', medal);
}
});
socket.on('disconnect', () => {
socket.broadcast.emit('remove-player', socket.id);
currPlayers = currPlayers.filter(player => player.id !== socket.id);
});
});
module.exports = app; // For testing