-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
239 lines (207 loc) · 7.34 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var gameInstance = require('./js/game-instance');
var uuidv1 = require('uuid/v1');
var sqlite3 = require('sqlite3').verbose();
// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 5000;
const MAX_PLAYERS = 3;
var db = new sqlite3.Database('highscores.db');
function writeHighScores(scores) {
db.serialize(function () {
db.run("CREATE TABLE IF NOT EXISTS highscores(player_name TEXT NOT NULL, score INTEGER NOT NULL)");
var stmt = db.prepare("INSERT INTO highscores VALUES (?,?)")
for (let i = 0; i < scores.length; i++) {
const score = scores[i];
stmt.run(score.name, score.score);
}
stmt.finalize();
});
}
function sendHighScores(socket, number) {
var scores = [];
var limitString = '';
if(number){
limitString = ` LIMIT ${number}`;
}
db.serialize(function () {
db.each("SELECT rowid AS id, player_name, score FROM highscores ORDER BY score DESC" + limitString, function (err, row) {
if(err) {
}
scores.push({ name: row.player_name, score: row.score });
}, function () {
//Send message in callback because db access is async
socket.emit('highScores', scores);
});
});
}
var rooms = [];
var games = {};
var clients = {};
const ClientStatus = {
WAITING_TO_START: 'waiting_to_join',
CONNECTED: 'connected',
DISCONNECTED: 'disconnected',
READY: 'ready',
PLAYING: 'playing'
};
function createRoom() {
var id = uuidv1();
var room = {
roomID: id,
clients: [],
game: null
};
rooms.push(room);
return room;
};
function getFirstAvailableRoom() {
for (let i = 0; i < rooms.length; i++) {
const room = rooms[i];
if (room.clients.length < MAX_PLAYERS) {
return room;
}
}
//No available room, make a new one
return createRoom();
};
function onRequestNewGame(socket) {
clients[socket.id].uniqueID = uuidv1();
//Tell the client we are finding a room
socket.emit('id', clients[socket.id].uniqueID);
socket.emit('waitingForRoom');
var room = getFirstAvailableRoom();
clients[socket.id].room = room;
clients[socket.id].status = ClientStatus.WAITING_TO_START;
socket.join(room.roomID);
room.clients.push(clients[socket.id]);
socket.emit('waitingToStart', { id: room.roomID, playerCount: room.clients.length, maxPlayers: MAX_PLAYERS });
socket.on('waitingToStart', function () {
setTimeout(function () {
if(socket.id in clients){
var room = clients[socket.id].room;
if (room && room.clients.length == MAX_PLAYERS) {
socket.emit('readyToStart');
socket.on('confirmReady', function () {
clients[socket.id].status = ClientStatus.READY;
startGame(socket, room);
});
}
else {
socket.emit('waitingToStart', { id: room.roomID, playerCount: room.clients.length, maxPlayers: MAX_PLAYERS });
}
}
}, 250);
});
};
function startGame(socket, room) {
socket.on('playerUpdate', function (updateData) {
var client = clients[socket.id];
if (client.room && client.room.game) {
client.room.game.UpdatePlayer(client.uniqueID, updateData);
}
});
if (room.clients.every(client => client.status == ClientStatus.READY)) {
room.game = new gameInstance(io, room.roomID);
room.game.on('GameFinished', function (scores) {
room.game.removeAllListeners();
room.game = null;
for (let i = 0; i < room.clients.length; i++) {
var client = room.clients[i];
client.room = null;
client.status = ClientStatus.CONNECTED;
}
for (let i = 0; i < rooms.length; i++) {
const r = rooms[i];
if (r === room) {
rooms.splice(i, 1);
}
}
writeHighScores(scores);
});
room.clients.forEach(client => room.game.AddPlayer(client.uniqueID, client.name));
io.to(room.roomID).emit('gameStarted');
io.to(room.roomID).emit('currentPlayers', room.game.GetAllPlayersState());
io.to(room.roomID).emit('currentBullets', room.game.GetAllBulletState());
room.game.Start();
}
};
(function () {
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
setInterval(function()
{
console.log(`Rooms running: ${rooms.length} Connected Clients: ${Object.keys(clients).length}`)
},10000);
io.on('connection', function (socket) {
clients[socket.id] = {
socketID: socket.id,
uniqueID: '',
status: ClientStatus.CONNECTED,
room: null,
name: ''
};
console.log('a user connected');
socket.on('error', function(err){
console.log(err);
})
socket.on('playerName', function (name) {
var client = clients[socket.id];
if (client) client.name = name;
});
socket.on('requestHighScores', function (number) {
sendHighScores(socket, number);
});
socket.on('requestNewGame', function () {
onRequestNewGame(socket);
});
socket.on('requestRejoin', function (info) {
var room = rooms[info.room];
if (room) {
if (!room.game.PlayerReconnected(info.id)) {
socket.emit('FailedToReconnect', 'ID is not valid for this room');
}
else {
clients[socket.id].uniqueID = info.id;
clients[socket.id].room = room;
socket.emit('explosionHistory', room.game.GetExplosionHistory());
socket.emit('ReconnectSuccessful');
}
}
else {
socket.emit('FailedToReconnect', 'Invalid Room');
}
});
socket.on('disconnect', function () {
console.log('user disconnected');
var client = clients[socket.id];
if (socket.id in clients && client) {
var room = clients[socket.id].room;
switch (client.status) {
case ClientStatus.WAITING_TO_START:
if (room) {
room.clients.splice(room.clients.indexOf(client), 1);
}
break;
case ClientStatus.READY:
case ClientStatus.PLAYING:
if (room && room.game) {
room.game.PlayerDisconnected(clients[socket.id].uniqueID);
}
break;
default:
break;
}
delete clients[socket.id];
}
});
});
server.listen(port, function () {
console.log(`Listening on ${server.address().port}`);
});
}());