aboutsummaryrefslogtreecommitdiff
path: root/src/quiz-bunny/server.js
blob: 0725fdca74dcb2d374da0185233685d27b349bfe (plain)
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
const uuidv4 = require('uuid/v4');
const words = require('./words').words;
const prompts = require('./prompts').prompts;

function setUpRoutes(server, models, jwtFunctions, database) {
    // simple send files
    server.get('/quiz-bunny', (req, res) => res.sendFile(__dirname + "/index.html"))
    server.get('/quiz-bunny/main.js', (req, res) => res.sendFile(__dirname + "/static/main.js"))
    server.get('/quiz-bunny/styles.css', (req, res) => res.sendFile(__dirname + "/static/styles.css"))
    server.get('/quiz-bunny/bunny.jpg', (req, res) => res.sendFile(__dirname + "/static/bunny.jpg"))

    // a list of games
    var games = []
    let STATES = {
        TYPING: 0,
        VOTING: 1,
        OVER: 2,
        WAITING: 3,
    }

    // generates a game code
    function generateGameCode() {
        // let words = ["cat", "dog"];
        var index = Math.floor(Math.random() * words.length)
        // ensure no duplicate game code
        while (games.find(el => el.gameCode == words[index].toLowerCase())) {
            var index = Math.floor(Math.random() * words.length)
        }
        return words[index].toLowerCase()
    }
    // gets a new game object
    function getNewGame(hostCookie, hostName) {
        let gameCode = generateGameCode();
        return {
            host: hostCookie,
            players: [{ cookie: hostCookie, name: hostName }],
            gameCode: gameCode,
            maxRound: 8
        }
    }
    // adds a player to a game object
    function addToGame(gameCode, playerCookie, playerName) {
        let game = games.find(el => el.gameCode == gameCode)
        if (game) {
            game.players.push({ cookie: playerCookie, name: playerName })
            return true
        }
        return false
    }
    function findGameByCookie(cookie) {
        return games.find(el => el.players.some(player => player.cookie == cookie))
    }
    function findPlayerByCookie(game, cookie) {
        return game.players.find(player => player.cookie == cookie)
    }
    function getPlayerNames(players) {
        // return players.map(player => player.name)
        return players.map(player => {
            return { name: player.name, ready: player.ready }
        })
    }
    // Turn the game into a public game object (no cookies, etc.)
    function getPublicGame(cookie) {
        var game = findGameByCookie(cookie)
        if (!game) {
            return { message: "no game active" }
        } else {
            let isHost = cookie == game.host
            let username = game.players.find(player => player.cookie == cookie).name
            let players = getPlayerNames(game.players)
            // console.log(players)
            var newGame = {
                host: isHost,
                players: players,
                name: username,
                gameCode: game.gameCode,
                gameStarted: game.gameStarted,
                state: game.state,
                round: game.round,
                maxRound: game.maxRound
            }
            if (game.state == STATES.TYPING) {
                newGame.submitted = game.answers.some(answer => answer.cookie == cookie)
                newGame.prompt = game.prompts[game.round]
                newGame.players.forEach(player => {
                    var playerWithCookie = game.players.find(p => {
                        return p.name == player.name
                    })
                    if (game.answers.some(answer => answer.cookie == playerWithCookie.cookie)) {
                        player.ready = true
                    } else {
                        player.ready = false
                    }
                })
            } else if (game.state == STATES.VOTING) {
                newGame.answers = game.answers.map(answer => answer.text)
                newGame.prompt = game.prompts[game.round]
                var game = findGameByCookie(cookie)
                var player = findPlayerByCookie(game, cookie)
                newGame.voted = player.voted
                newGame.players.forEach(player => {
                    var playerWithCookie = game.players.find(p => {
                        return p.name == player.name
                    })
                    player.ready = playerWithCookie.voted
                })
            } else if (game.state == STATES.WAITING) {
                newGame.answers = game.answers.map(answer => {
                    return {
                        text: answer.text,
                        voteCount: answer.votes.length,
                        voteNames: answer.votes.map(vote => vote.name),
                        name: findPlayerByCookie(game, answer.cookie).name
                    }
                })
                newGame.prompt = game.prompts[game.round]
                var game = findGameByCookie(cookie)
                var player = findPlayerByCookie(game, cookie)
                newGame.ready = player.ready
            } else if (game.state == STATES.OVER) {
                var scores = game.players.map(player => {
                    return { name: player.name, score: player.score }
                })
                // sort
                scores.sort((a, b) => b.score - a.score);
                newGame.scores = scores
            }

            return newGame
        }
    }
    function shuffle(a) {
        var j, x, i;
        for (i = a.length - 1; i > 0; i--) {
            j = Math.floor(Math.random() * (i + 1));
            x = a[i];
            a[i] = a[j];
            a[j] = x;
        }
        return a;
    }
    function getRandomPlayer(stack, playersList) {
        if (stack.length == 0) {
            for (var i = 0; i < playersList.length; i++) {
                stack.push(playersList[i])
            }
            shuffle(stack)
        }
        return stack.shift()
    }
    // gets a game prompt
    function getPrompts(playerNames, size) {
        var gamePrompts = []
        var stack = []
        while (gamePrompts.length < size) {
            var randomIndex = Math.floor(Math.random() * prompts.length)
            var prompt = prompts[randomIndex]
            while (prompt.includes("@")) {
                prompt = prompt.replace("@", getRandomPlayer(stack, playerNames))
            }
            if (gamePrompts.indexOf(prompt) == -1) {
                gamePrompts.push(prompt)
            }
        }
        return gamePrompts
    }
    // marks the game as started
    function startGame(cookie) {
        let game = games.find(el => el.host == cookie)
        if (game && game.players.length >= 2) {
            game.gameStarted = true
            var playerNames = game.players.map(player => player.name)
            game.prompts = getPrompts(playerNames, game.maxRound)
            game.round = 0;
            game.players.forEach(player => {
                player.score = 0
            })
            game.state = STATES.TYPING
            startRound(game);
            return true
        } else {
            return false
        }
    }
    function startRound(game) {
        // keep track of votes
        game.players.forEach(player => {
            player.voted = false
        })
        game.answers = []
        game.state = STATES.TYPING
    }
    function submitAnswer(cookie, text) {
        let game = findGameByCookie(cookie)
        if (!game.answers.some(answer => answer.cookie == cookie)) {
            game.answers.push({ text: text, cookie: cookie })
        }
        if (game.answers.length == game.players.length) {
            startVoting(game)
        }
    }
    function startVoting(game) {
        game.state = STATES.VOTING
        game.answers.forEach(answer => {
            answer.votes = []
        })
        shuffle(game.answers)
        game.voteCount = 0
    }
    function endVoting(game) {
        game.state = STATES.WAITING
        game.players.forEach(player => {
            player.ready = false
        })
        game.answers.forEach(answer => {
            var player = findPlayerByCookie(game, answer.cookie)
            player.score += answer.votes.length
            // extra points for high scoring answer
            if (answer.votes.length >= 3) {
                player.score += 2
            }
        })
    }
    function endRound(game) {
        game.round += 1
        if (game.round >= game.prompts.length) {
            game.state = STATES.OVER
        } else {
            startRound(game)
        }
    }
    // player with cookie votes for answer 
    function voteFor(cookie, answerIndex) {
        let game = findGameByCookie(cookie)
        let playerWhoVoted = findPlayerByCookie(game, cookie)
        let answer = game.answers[answerIndex]
        // If already voted, or voted for self, ignore
        if (playerWhoVoted.voted || answer.cookie == cookie) {
            return false
        }
        playerWhoVoted.voted = true
        answer.votes.push(playerWhoVoted)
        game.voteCount++
        if (game.voteCount == game.players.length) {
            endVoting(game)
        }
        return true
    }
    function ready(cookie) {
        let game = findGameByCookie(cookie)
        let player = findPlayerByCookie(game, cookie)
        player.ready = true
        if (game.players.every(player => player.ready)) {
            endRound(game)
        }
    }
    // Requested by host once
    server.get('/quiz-bunny/host-game', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie) {
            cookie = uuidv4();
            res.cookie('session', cookie, { expires: new Date(Date.now() + (1000 * 60 * 60)) });
        }
        let username = req.query.name
        var game = getNewGame(cookie, username)
        games.push(game)
        res.status(200).send(getPublicGame(cookie))
    })
    // Requested by players joining from game code
    server.get('/quiz-bunny/join-game', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie) {
            cookie = uuidv4();
            res.cookie('session', cookie, { expires: new Date(Date.now() + (1000 * 60 * 60)) });
        }
        let username = req.query.name
        let code = req.query.code
        if (addToGame(code, cookie, username)) {
            res.status(200).send(getPublicGame(cookie))
        } else {
            res.status(200).send({ message: "Invalid game code" })
        }
    })
    // starts the game
    server.get('/quiz-bunny/start-game', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie || !startGame(cookie)) {
            res.status(400).send({ message: "you cannot start a game" });
        } else {
            res.status(200).send(getPublicGame(cookie))
        }
    })
    // constantly requested by client while in lobby
    server.get('/quiz-bunny/lobby-status', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            res.status(200).send(getPublicGame(cookie))
        }
    })
    // constantly requested by client while game started
    server.get('/quiz-bunny/game-status', (req, res, next) => {
        // TODO
        let cookie = req.cookies.session;
        if (!cookie) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            var game = findGameByCookie(cookie)
            res.status(200).send(getPublicGame(cookie))
            // if(game.state == STATES.TYPING) {
            // } else if(game.state == STATES.VOTING) {
            // } else if(game.state == STATES.WAITING) {
            // }
        }
    })
    server.get('/quiz-bunny/vote', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie || req.query.index == undefined) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            voteFor(cookie, req.query.index)
            res.status(200).send()
        }
    })
    server.get('/quiz-bunny/submit', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie || req.query.text == undefined) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            submitAnswer(cookie, req.query.text)
            res.status(200).send()
        }
    })
    server.get('/quiz-bunny/ready', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            ready(cookie)
            res.status(200).send()
        }
    })
    server.get('/quiz-bunny/ready', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            ready(cookie)
            res.status(200).send()
        }
    })
    server.get('/quiz-bunny/leave', (req, res, next) => {
        let cookie = req.cookies.session;
        if (!cookie) {
            res.status(400).send({ message: "you are not in a game" });
        } else {
            var game = findGameByCookie(cookie)
            game.players = game.players.filter(player => player.cookie != cookie)
            if (game.players.length == 0) {
                games = games.filter(g => g != game)
            }
            res.status(200).send()
        }
    })
}

module.exports = {
    setUpRoutes
};