Add Winnings Functionality

Video Lecture

Add Winnings Functionality Add Winnings Functionality

dist/client/index.html

Add the Winners/Losers Alerting Panels

  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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
<! DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <title>TypeScript Socket.IO Course</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">

    <style>
        .timer {
            font-size: 4em;
            position: absolute;
            right: 15px;
            top: -15px;
        }

        .gamephase {
            font-size: 1.75em;
        }

        .playerGuess {
            font-size: 1.5em;
        }

        .goodLuckMessage {
            font-size: 1.5em;
            padding-left: 10px;
            display: none;
        }

        .progress-container {
            width: 100%;
            height: 8px;
            background: #ccc;
            margin-top: 40px;
            border: solid 1px gray;
        }

        .progress-bar {
            height: 8px;
            background: #4caf50;
            width: 0%;
        }

        .gamePanel {
            position: relative;
            border: solid 1px gray;
            height: 382px;
            border-radius: 0px 20px 4px 20px;
            box-shadow: 15px 10px #dddddd;
        }

        #gamePanel0 {
            display: block;
            background: linear-gradient(180deg, rgba(195, 112, 34, 0.164) 0%, rgba(156, 200, 105, 0.495) 100%);
        }

        #gamePanel1 {
            display: none;
            background: linear-gradient(56deg, rgba(225, 238, 255, 0.492) 0%, rgba(122, 67, 250, 0.495) 100%);
        }

        #gamePanel2 {
            display: none;
            background: linear-gradient(56deg, rgba(235, 204, 32, 0.492) 0%, rgba(251, 188, 106, 0.495) 100%);
        }

        .chatPanel {
            border: solid 1px gray;
            border-radius: 20px 0px 4px 4px;
            box-shadow: 15px 10px #dddddd;
            background: rgb(34, 193, 195);
            background: linear-gradient(56deg, rgba(34, 193, 195, 0.49193275943189773) 0%, rgba(253, 187, 45, 0.494733879880077) 100%);
            position: relative;
        }

        .chatMessageInputDiv {
            position: absolute;
            bottom: 0px;
            width: 100%;
        }

        .messages {
            padding-left: 0;
            overflow: hidden;
            height: 340px;
            margin-bottom: 40px;
        }

        .messages li {
            list-style-type: none;
            margin-bottom: 30px;
            padding: 6px 6px 6px 6px;
            display: block
        }

        .otherMessage {
            background: #ffcda3;
            border: solid 1px gray;
            margin: 0px 5px 5px 0px;
            float: right;
            padding: 0px 6px 0px 6px;
            border-radius: 10px 10px 0 10px;
        }

        .myMessage {
            background: #1bffbb;
            border: solid 1px gray;
            margin: 0px 5px 5px 5px;
            float: left;
            padding: 0px 6px 0px 6px;
            border-radius: 10px 10px 10px 0;
        }

        .gameMessage {
            background: #1babff;
            border: solid 1px gray;
            margin: 0px 5px 5px 5px;
            float: left;
            padding: 0px 6px 0px 6px;
            border-radius: 10px 10px 10px 0;
        }

        .screenName {
            padding: 6px 6px 6px 6px;
            border-radius: 10px 10px 10px 10px;
            font-weight: bold;
            background: #1bffbb;
        }

        .score {
            padding: 6px 6px 6px 6px;
            border-radius: 10px 10px 10px 10px;
            font-weight: bold;
            background: #1bffbb;
        }

        .circle {
            padding: 6px;
            background: gray;
            border-radius: 50px;
        }

        .resultValue {
            font-size: 3.5em;
            width: 100%;
            text-align: center;
        }

        @keyframes spinner {
            to {
                transform: rotate(360deg);
            }
        }

        .spinner:before {
            content: '';
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            left: 50%;
            width: 90px;
            height: 90px;
            margin-top: -45px;
            margin-left: -45px;
            border-radius: 50%;
            border: 10px solid #f6f;
            border-top-color: #0e0;
            border-right-color: #0dd;
            border-bottom-color: #f90;
            animation: spinner .6s linear infinite;
        }

        .jumbotron {
            margin-top: -40px;
            height: 180px;
        }

        .footer {
            margin-top: 10px;
        }

        @keyframes glowing {
            0% {
                background-color: #2ba805;
                box-shadow: 0 0 5px #2ba805;
            }

            50% {
                background-color: #ff0080;
                box-shadow: 0 0 20px #ffa600;
            }

            100% {
                background-color: #2ba805;
                box-shadow: 0 0 5px #2ba805;
            }
        }
    </style>

</head>

<body>

    <div class="jumbotron text-center" style="margin-bottom:0">
        <h1>Lucky Numbers Mini-Games</h1>
        <p><a href="https://sbcode.net/tssock" target="_blank">https://sbcode.net/tssock</a>
        </p>
    </div>

    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
        <a class="navbar-brand" href="#">Games</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="#" onclick="client.showGame(0)">πŸ₯‰Bronze Game</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" onclick="client.showGame(1)">πŸ₯ˆSilver Game</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" onclick="client.showGame(2)">πŸ₯‡Gold Game</a>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container" style="margin-top:30px">
        <div class="row">
            <div class="col-sm-8">
                <div class="gamePanel" id="gamePanel0">
                    <h2 id="gameTitle">πŸ₯‰Bronze Game</h2>
                    <span id="timer0" class="timer"></span>
                    <div class="progress-container">
                        <div class="progress-bar" id="timerBar0"></div>
                    </div>
                    <div id="gamephase0" class="gamephase p-2"></div>
                    <div class="p-2">Your Screen Name is <span class="screenName"></span>, and your Score is <span class="score"></span></div>
                    <div class="p-2">Your guesses
                        <button class="button btn btn-success" onClick="client.submitGuess(0,1)"
                            id="submitButton00">1</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,2)"
                            id="submitButton01">2</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,3)"
                            id="submitButton02">3</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,4)"
                            id="submitButton03">4</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,5)"
                            id="submitButton04">5</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,6)"
                            id="submitButton05">6</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,7)"
                            id="submitButton06">7</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,8)"
                            id="submitButton07">8</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,9)"
                            id="submitButton08">9</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(0,10)"
                            id="submitButton09">10</button>
                        <span id="goodLuckMessage0" class="goodLuckMessage">Good Luck 🀞</span>
                    </div>
                    <div class="row">
                        <div class="col-sm-4">
                            <div class="m-2">
                                <div id="resultAlert0" class="alert alert-info" role="alert">
                                    <h1 class="alert-heading p-1 resultValue" id="resultValue0"></h1>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-8">
                            <div class="m-2">
                                <div id="winnerAlert0" class="alert alert-success p-3" role="alert">
                                    <h4 class="alert-heading">You Win! πŸ†</h4>
                                    <p>You guessed the correct number</p>
                                </div>
                                <div id="looserAlert0" class="alert alert-danger p-3" role="alert">
                                    <h4 class="alert-heading">You Loose! πŸ‘Ž</h4>
                                    <p>You guessed incorrectly. Get back on your 🐎</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="gamePanel" id="gamePanel1">
                    <h2 id="gameTitle">πŸ₯ˆSilver Game</h2>
                    <span id="timer1" class="timer"></span>
                    <div class="progress-container">
                        <div class="progress-bar" id="timerBar1"></div>
                    </div>
                    <div id="gamephase1" class="gamephase p-2"></div>
                    <div class="p-2">Your Screen Name is <span class="screenName"></span>, and your Score is <span class="score"></span></div>
                    <div class="p-2">Your guesses
                        <button class="button btn btn-success" onClick="client.submitGuess(1,1)"
                            id="submitButton10">1</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,2)"
                            id="submitButton11">2</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,3)"
                            id="submitButton12">3</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,4)"
                            id="submitButton13">4</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,5)"
                            id="submitButton14">5</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,6)"
                            id="submitButton15">6</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,7)"
                            id="submitButton16">7</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,8)"
                            id="submitButton17">8</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,9)"
                            id="submitButton18">9</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(1,10)"
                            id="submitButton19">10</button>
                        <span id="goodLuckMessage1" class="goodLuckMessage">Good Luck 🀞</span>
                    </div>
                    <div class="row">
                        <div class="col-sm-4">
                            <div class="m-2">
                                <div id="resultAlert1" class="alert alert-info" role="alert">
                                    <h1 class="alert-heading p-1 resultValue" id="resultValue1"></h1>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-8">
                            <div class="m-2">
                                <div id="winnerAlert1" class="alert alert-success p-3" role="alert">
                                    <h4 class="alert-heading">You Win! πŸ†</h4>
                                    <p>You guessed the correct number</p>
                                </div>
                                <div id="looserAlert1" class="alert alert-danger p-3" role="alert">
                                    <h4 class="alert-heading">You Loose! πŸ‘Ž</h4>
                                    <p>You guessed incorrectly. Get back on your 🐎</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="gamePanel" id="gamePanel2">
                    <h2 id="gameTitle">πŸ₯‡Gold Game</h2>
                    <span id="timer2" class="timer"></span>
                    <div class="progress-container">
                        <div class="progress-bar" id="timerBar2"></div>
                    </div>
                    <div id="gamephase2" class="gamephase p-2"></div>
                    <div class="p-2">Your Screen Name is <span class="screenName"></span>, and your Score is <span class="score"></span></div>
                    <div class="p-2">Your guesses
                        <button class="button btn btn-success" onClick="client.submitGuess(2,1)"
                            id="submitButton20">1</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,2)"
                            id="submitButton21">2</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,3)"
                            id="submitButton22">3</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,4)"
                            id="submitButton23">4</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,5)"
                            id="submitButton24">5</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,6)"
                            id="submitButton25">6</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,7)"
                            id="submitButton26">7</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,8)"
                            id="submitButton27">8</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,9)"
                            id="submitButton28">9</button>
                        <button class="button btn btn-success" onClick="client.submitGuess(2,10)"
                            id="submitButton29">10</button>
                        <span id="goodLuckMessage2" class="goodLuckMessage">Good Luck 🀞</span>
                    </div>
                    <div class="row">
                        <div class="col-sm-4">
                            <div class="m-2">
                                <div id="resultAlert2" class="alert alert-info" role="alert">
                                    <h1 class="alert-heading p-1 resultValue" id="resultValue2"></h1>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-8">
                            <div class="m-2">
                                <div id="winnerAlert2" class="alert alert-success p-3" role="alert">
                                    <h4 class="alert-heading">You Win! πŸ†</h4>
                                    <p>You guessed the correct number</p>
                                </div>
                                <div id="looserAlert2" class="alert alert-danger p-3" role="alert">
                                    <h4 class="alert-heading">You Loose! πŸ‘Ž</h4>
                                    <p>You guessed incorrectly. Get back on your 🐎</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-4">
                <div class="chatPanel">
                    <ol id="messages" class="messages">
                    </ol>
                    <div class="chatMessageInputDiv">
                        <div class="input-group">
                            <input class="form-control width100" id="messageText" placeholder="Enter Chat Message" onkeyup="">
                            <span class="input-group-btn">
                                <button class="btn btn-info" onclick="client.sendMessage()">Send</button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="footer text-center" style="margin-bottom:0">
        This is an example game from the TypeScript SocketIO course at <a href="https://sbcode.net/tssock" target="_blank">https://sbcode.net/tssock</a>
    </div>

    <script src="jquery/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="socket.io/socket.io.js"></script>
    <script src="client.js"></script>

</body>

</html>

src/client/client.ts

Add winners properties to GameState, create loginc to show Winners and Loosers panels, and default the Winners and Loosers panels to be hidden on document ready.

  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
type ChatMessage = {

    message: string
    from: string
    type: "playerMessage" | "gameMessage"

}

type ScreenName = {

    name: string
    abbreviation: string

}

type Player = {

    score: number
    screenName: ScreenName

}

type GameState = {

    id: number
    title: string
    logo: string
    gamePhase: number
    gameClock: number
    duration: number
    result: number
    winners: string[]
    winnersCalculated: boolean

}

class Client {

    private socket: SocketIOClient.Socket
    private player: Player
    private inThisRound: boolean[] = [false, false, false]
    private alertedWinnersLoosers: boolean[] = [false, false, false]

    constructor() {
        this.socket = io();

        this.socket.on("connect", function () {
            console.log("connect")
        })

        this.socket.on("disconnect", function (message: any) {
            console.log("disconnect " + message)
            location.reload();
        })

        this.socket.on("GameStates", (gameStates: GameState[]) => {
            //console.dir(gameStates)
            gameStates.forEach(gameState => {
                let gid = gameState.id
                if (gameState.gameClock >= 0) {
                    if (gameState.gameClock >= gameState.duration) {
                        $("#gamephase" + gid).text("New Game, Guess the Lucky Number")
                        this.alertedWinnersLoosers[gid] = false
                        for (let x = 0; x < 10; x++) {
                            $("#submitButton" + gid + x).prop("disabled", false);
                        }
                    }
                    if (gameState.gameClock === gameState.duration - 5) {                       
                        $('#resultAlert' + gid).alert().fadeOut(500)
                        $('#winnerAlert' + gid).alert().fadeOut(500)
                        $('#looserAlert' + gid).alert().fadeOut(500)
                    }
                    $("#timer" + gid).css("display", "block")
                    $("#timer" + gid).text(gameState.gameClock.toString())
                    var progressParent = (gameState.gameClock / gameState.duration) * 100;
                    $("#timerBar" + gid).css("background-color", "#4caf50")
                    $("#timerBar" + gid).css("width", progressParent + "%")
                } else {
                    $("#timerBar" + gid).css("background-color", "#ff0000")
                    $("#timerBar" + gid).css("width", "100%")
                    $("#timer" + gid).css("display", "none")
                    $("#gamephase" + gid).text("Game Closed")
                    for (let x = 0; x < 10; x++) {
                        $("#submitButton" + gid + x).prop("disabled", true);
                    }
                    $("#goodLuckMessage" + gid).css("display", "none")

                    if (gameState.gameClock === -2 && gameState.result !== -1) {
                        $('#resultValue' + gid).text(gameState.result)
                        $('#resultAlert' + gid).fadeIn(100)   
                        $('#submitButton' + gid + (gameState.result - 1)).css("animation", "glowing 1000ms infinite");
                        setTimeout(() => {
                            $('#submitButton' + gid + (gameState.result - 1)).css("animation", "")
                        }, 4000)                     
                    }

                    if (this.inThisRound[gid] && !this.alertedWinnersLoosers[gid] && gameState.winnersCalculated) {
                        this.inThisRound[gid] = false;
                        if (gameState.winners.includes(this.socket.id)) {
                            $('#winnerAlert' + gid).fadeIn(100)
                        } else {
                            $('#looserAlert' + gid).fadeIn(100)
                        }

                        this.alertedWinnersLoosers[gid] = true
                    }
                }
            })
        })

        this.socket.on("playerDetails", (player: Player) => {
            this.player = player
            $(".screenName").text(player.screenName.name)
            $(".score").text(player.score)
        })

        this.socket.on("confirmGuess", (gameId: number, guess: number, score: number) => {
            this.inThisRound[gameId] = true
            $("#submitButton" + gameId + (guess - 1)).prop("disabled", true);
            $("#goodLuckMessage" + gameId).css("display", "inline-block")
            $(".score").text(score)
        })

        this.socket.on("chatMessage", (chatMessage: ChatMessage) => {
            if (chatMessage.type === "gameMessage") {
                $("#messages").append("<li><span class='float-left'><span class='circle'>" + chatMessage.from + "</span></span><div class='gameMessage'>" + chatMessage.message + "</div></li>")
            } else { 
                $("#messages").append("<li><span class='float-right'><span class='circle'>" + chatMessage.from + "</span></span><div class='otherMessage'>" + chatMessage.message + "</div></li>")
            }
            this.scrollChatWindow()
        })

        $(document).ready(() => {
            $('#resultValue0').addClass('spinner');
            $('#resultValue1').addClass('spinner');
            $('#resultValue2').addClass('spinner');
            $('#resultAlert0').alert().hide()
            $('#resultAlert1').alert().hide()
            $('#resultAlert2').alert().hide()
            $('#winnerAlert0').alert().hide()
            $('#winnerAlert1').alert().hide()
            $('#winnerAlert2').alert().hide()
            $('#looserAlert0').alert().hide()
            $('#looserAlert1').alert().hide()
            $('#looserAlert2').alert().hide()

            $('#messageText').keypress((e) => {
                var key = e.which;
                if (key == 13)  // the enter key code
                {
                    this.sendMessage()
                    return false;
                }
            });
        })
    }

    public submitGuess(gameId: number, guess: number) {
        this.socket.emit("submitGuess", gameId, guess)
    }

    private scrollChatWindow = () => {
        $('#messages').animate({
            scrollTop: $('#messages li:last-child').position().top
        }, 500);
        setTimeout(() => {
            let messagesLength = $("#messages li");
            if (messagesLength.length > 10) {
                messagesLength.eq(0).remove();
            }
        }, 500)
    }

    public sendMessage() {
        let messageText = $("#messageText").val();
        if (messageText.toString().length > 0) {

            this.socket.emit("chatMessage", <ChatMessage>{ message: messageText, from: this.player.screenName.abbreviation })

            $("#messages").append("<li><span class='float-left'><span class='circle'>" + this.player.screenName.abbreviation + "</span></span><div class='myMessage'>" + messageText + "</div></li>")
            this.scrollChatWindow()

            $("#messageText").val("");
        }
    }

    public showGame(id: number) {
        switch (id) {
            case 0:
                $("#gamePanel1").fadeOut(100)
                $("#gamePanel2").fadeOut(100)
                $("#gamePanel0").delay(100).fadeIn(100)
                break;
            case 1:
                $("#gamePanel0").fadeOut(100)
                $("#gamePanel2").fadeOut(100)
                $("#gamePanel1").delay(100).fadeIn(100)
                break;
            case 2:
                $("#gamePanel0").fadeOut(100)
                $("#gamePanel1").fadeOut(100)
                $("#gamePanel2").delay(100).fadeIn(100)
                break;
        }
    }

}

const client = new Client(); 

src/server/gameState.ts

Add extra winners properties to the server GameState

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type GameState = {

    id: number
    title: string
    logo: string
    gamePhase: number
    gameClock: number
    duration: number
    result: number
    winners: string[]
    winnersCalculated: boolean

}

src/server/luckyNumbersGame.ts

Create Winner properties, add a constructor argument to set the winning amount for the game, add another callback to update the players score upon winning a game.

  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
import Player from "./player"

export default class LuckyNumbersGame {

    private _id: number
    private _title: string
    private _logo: string
    private _duration: number
    private _gamePhase: number = 0
    private _gameClock: number = 0
    private _gameState: GameState
    private _result: number = -1
    private _players: { [id: string]: Player } = {}
    private _guesses: { [id: string]: number[] } = {}    
    private _enterPoints: number
    private _winPoints: number
    private _winners: string[]
    private _winnersCalculated: boolean = false
    private _updateChatCallBack: (chatMessage: ChatMessage) => void
    private _sendPlayerDetailsCB: (playerSocketID: string) => void

    constructor(id: number,
        title: string,
        logo: string,
        duration: number,
        enterPoints: number,
        winPoints: number,
        players: { [id: string]: Player },
        updateChatCallBack: (chatMessage: ChatMessage) => void,
        sendPlayerDetailsCB: (playerSocketID: string) => void
    ) {
        this._id = id
        this._title = title
        this._logo = logo
        this._duration = duration
        this._players = players
        this._enterPoints = enterPoints
        this._winPoints = winPoints
        this._updateChatCallBack = updateChatCallBack
        this._sendPlayerDetailsCB = sendPlayerDetailsCB

        setInterval(() => {
            if (this._gamePhase === 0) {
                this._gameClock = this._duration
                this._gamePhase = 1
                this._result = -1
                this._winners = []
                this._winnersCalculated = false
                this._guesses = {}
                this._updateChatCallBack(<ChatMessage>{ message: "New Game", from: this._logo, type: "gameMessage" })            
            } else if (this._gamePhase === 1) {
                if (this._gameClock < 0) {
                    this._gamePhase = 2
                    this._updateChatCallBack(<ChatMessage>{ message: "Game Closed", from: this._logo, type: "gameMessage" })
                }
            } else if (this._gamePhase === 2) {
                if (this._gameClock === -2) {
                    this._result = (Math.floor(Math.random() * 10) + 1)
                    this._updateChatCallBack(<ChatMessage>{ message: "Result : " + this._result, from: this._logo, type: "gameMessage" })
                } else if (this._gameClock === -3) {
                    //get winners   
                    this._winners = this.calculateWinners(this._result)
                    this._winners.forEach(w => {
                        this._players[w].adjustScore(this._winPoints)
                        this._sendPlayerDetailsCB(w)
                    })
                    this._winnersCalculated = true
                } else if (this._gameClock <= -5) {
                    this._gamePhase = 0
                }
            }
            this._gameState = { id: this._id, title: this._title, logo: this._logo, gamePhase: this._gamePhase, gameClock: this._gameClock, duration: this._duration, result: this._result, winners: this._winners, winnersCalculated: this._winnersCalculated }
            this._gameClock -= 1
        }, 1000)
    }

    public get gameState() {
        return this._gameState
    }

    public submitGuess(playerSocketId: string, guess: number): boolean {
        if (!this._guesses[playerSocketId]) {
            this._guesses[playerSocketId] = []
        }
        this._players[playerSocketId].adjustScore(this._enterPoints * -1)
        this._guesses[playerSocketId].push(guess)
        if (this._guesses[playerSocketId].length === 1) {
            let chatMessage = <ChatMessage>{ message: this._players[playerSocketId].screenName.name + " is playing", from: this._logo, type: "gameMessage" }
            this._updateChatCallBack(chatMessage)
        }
        return true;
    }

    private calculateWinners(number: number): string[] {
        let ret: string[] = []
        for (let playerSocketId in this._guesses) {
            for (let guess in this._guesses[playerSocketId]) {
                if (number === this._guesses[playerSocketId][guess]) {
                    ret.push(playerSocketId)
                }
            }
        }
        return ret
    }

}

src/server/server.ts

Add the games winning amount and sendPlayerDetails callback to the games instantiation calls.

 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
import express from "express"
import path from "path"
import http from "http"
import socketIO from "socket.io"
import LuckyNumbersGame from "./luckyNumbersGame"
import RandomScreenNameGenerator from "./randomScreenNameGenerator"
import Player from "./player"

const port: number = 3000

class App {

    private server: http.Server
    private port: number

    private io: socketIO.Server
    private games: { [id: number]: LuckyNumbersGame } = {}
    private randomScreenNameGenerator: RandomScreenNameGenerator
    private players: { [id: string]: Player } = {}

    constructor(port: number) {
        this.port = port

        const app = express()
        app.use(express.static(path.join(__dirname, '../client')))
        app.use('/jquery', express.static(path.join(__dirname, '../../node_modules/jquery/dist')))
        app.use('/bootstrap', express.static(path.join(__dirname, '../../node_modules/bootstrap/dist')))

        this.server = new http.Server(app)
        this.io = socketIO(this.server);

        this.games[0] = new LuckyNumbersGame(0, "Bronze Game", "πŸ₯‰", 10, 1, 10, this.players, this.updateChat, this.sendPlayerDetails)
        this.games[1] = new LuckyNumbersGame(1, "Silver Game", "πŸ₯ˆ", 16, 2, 20, this.players, this.updateChat, this.sendPlayerDetails)
        this.games[2] = new LuckyNumbersGame(2, "Gold Game", "πŸ₯‡", 35, 10, 100, this.players, this.updateChat, this.sendPlayerDetails)

        this.randomScreenNameGenerator = new RandomScreenNameGenerator();

        this.io.on('connection', (socket: socketIO.Socket) => {
            console.log('a user connected : ' + socket.id)

            let screenName: ScreenName = this.randomScreenNameGenerator.generateRandomScreenName()

            this.players[socket.id] = new Player(screenName)

            socket.emit("playerDetails", this.players[socket.id].player)

            socket.on('disconnect', function () {
                console.log('socket disconnected : ' + socket.id);
                if (this.players && this.players[socket.id]) {
                    delete this.players[socket.id]
                }
            });

            socket.on('chatMessage', function (chatMessage: ChatMessage) {
                socket.broadcast.emit('chatMessage', chatMessage)
            });

            socket.on('submitGuess', (gameId: number, guess: number) => {
                if (guess >= 0 && guess <= 10) {
                    if (this.games[gameId].submitGuess(socket.id, guess)) {
                        socket.emit("confirmGuess", gameId, guess, this.players[socket.id].player.score)
                    }
                }
            })
        })

        setInterval(() => {
            this.io.emit("GameStates", [this.games[0].gameState, this.games[1].gameState, this.games[2].gameState])
        }, 1000)
    }

    public updateChat = (chatMessage: ChatMessage) => {
        this.io.emit('chatMessage', chatMessage)
    }

    public sendPlayerDetails = (playerSocketId: string) => {
        this.io.to(playerSocketId).emit("playerDetails", this.players[playerSocketId].player)
    }

    public Start() {
        this.server.listen(this.port)
        console.log( `Server listening on port ${this.port}.` )
    }

}

new App(port). Start()