Push Game Events to Chat

Video Lecture

Push Game Events to Chat Push Game Events to Chat Push Game Events to Chat

src/server/chatMessage.ts

1
2
3
4
5
6
7
type ChatMessage = {

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

}

src/server/server.ts

 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
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, this.updateChat)
        this.games[1] = new LuckyNumbersGame(1, "Silver Game", "🥈", 16, this.updateChat)
        this.games[2] = new LuckyNumbersGame(2, "Gold Game", "🥇", 35, this.updateChat)

        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)
            });
        })

        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 Start() {
        this.server.listen(this.port)
        console.log( `Server listening on port ${this.port}.` )
    }
}

new App(port).Start()

src/server/luckyNumbersGame.ts

 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
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 _updateChatCallBack: (chatMessage: ChatMessage) => void

    constructor(id: number,
        title: string,
        logo: string,
        duration: number,
        updateChatCallBack: (chatMessage: ChatMessage) => void,
    ) {
        this._id = id
        this._title = title
        this._logo = logo
        this._duration = duration
        this._updateChatCallBack = updateChatCallBack

        setInterval(() => {
            if (this._gamePhase === 0) {
                this._gameClock = this._duration
                this._gamePhase = 1
                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 <= -5) {
                    this._gamePhase = 0
                }
            }
            this._gameState = { id: this._id, title: this._title, logo: this._logo, gamePhase: this._gamePhase, gameClock: this._gameClock, duration: this._duration }
            this._gameClock -= 1
        }, 1000)
    }

    public get gameState() {
        return this._gameState
    }
}

src/client/client.ts

  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
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

}

class Client {

    private socket: SocketIOClient.Socket
    private player: Player

    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")
                    }
                    $("#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")
                }
            })
        })

        this.socket.on("playerDetails", (player: Player) => {
            this.player = player
            $(".screenName").text(player.screenName.name)
            $(".score").text(player.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(() => {
            $('#messageText').keypress((e) => {
                var key = e.which;
                if (key == 13)  // the enter key code
                {
                    this.sendMessage()
                    return false;
                }
            });
        })
    }

    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(); 

dist/client/index.html

  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
<! 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;
        }

        .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;
        }

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

        .footer {
            margin-top: 10px;
        }
    </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>
                <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>
                <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>
            </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>