lib/Server/memoryserver.js   A
last analyzed

Complexity

Total Complexity 32
Complexity/F 1.78

Size

Lines of Code 236
Function Count 18

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
nc 1
dl 0
loc 236
rs 9.6
noi 18
cc 0
wmc 32
mnd 7
bc 33
fnc 18
bpm 1.8333
cpm 1.7777

2 Functions

Rating   Name   Duplication   Size   Complexity  
A memoryserver.js ➔ ??? 0 7 1
A memoryserver.js ➔ ping 0 15 2
1
const WebSocket = require("ws");
2
const Memory = require('memorytest');
3
4
var usersobject = [];
5
let gameboard;
6
let gamebrain = new Memory.Gamebrain();
7
let memorycard = new Memory.Memorycard();
8
9
const wss = new WebSocket.Server({
10
    server: server,
0 ignored issues
show
Bug introduced by
The variable server seems to be never declared. If this is a global, consider adding a /** global: server */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
11
    clientTracking: true, // keep track on connected clients
12
});
13
14
wss.adduser = (nickname, ws) => {
15
    usersobject.push({
16
        name: nickname,
17
        isAlive: true,
18
        websocket: ws
19
    });
20
}
21
22
// When disconnecting controllably
23
wss.dropuser = (ws) => {
24
    var deletenick;
25
    var founduser = false;
26
27
    usersobject.forEach((userobj) => {
28
        if (userobj.websocket === ws) {
29
            founduser = true;
30
            console.log("Drop " + userobj.name);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
31
            deletenick = userobj.name;
32
            gamebrain.dropPlayer(deletenick);
33
        }
34
    });
35
36
    if (founduser) {
37
        usersobject = usersobject.filter(function(usr) {
38
           return usr.websocket !== ws;
39
        });
40
    }
41
}
42
43
// When connection is broken
44
wss.dropdead = () => {
45
    var deletenick;
46
    var founduser = false;
47
48
    usersobject.forEach((userobj) => {
49
        if (!userobj.isAlive) {
50
            founduser = true;
51
            console.log("Drop " + userobj.name);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
52
            deletenick = userobj.name;
53
            gamebrain.dropPlayer(deletenick);
54
        }
55
    });
56
57
    if (founduser) {
58
        usersobject = usersobject.filter(function(usr) {
59
           return usr.isAlive;
60
        });
61
        msg = {
0 ignored issues
show
Bug introduced by
The variable msg seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.msg.
Loading history...
62
            type: "users",
63
            userarray: gamebrain.getPlayersNicks(),
64
            userscolors: gamebrain.getPlayersColors()
65
        }
66
        wss.broadcastUsers(JSON.stringify(msg));
67
    }
68
}
69
70
71
72
// Broadcast data to everyone.
73
wss.broadcastUsers = (data) => {
74
    let clients = 0;
75
    wss.clients.forEach((client) => {
76
        clients++;
77
        client.send(data);
78
    });
79
    console.log(`Broadcasted users to ${clients} (${wss.clients.size}) clients.`);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
80
};
81
82
wss.answerBackWith = (data, ws) => {
83
    ws.send(data);
84
};
85
86
const interval = setInterval(function ping() {
0 ignored issues
show
Unused Code introduced by
The constant interval seems to be never used. Consider removing it.
Loading history...
87
    if (usersobject.length != wss.clients.size) {
88
        usersobject.forEach(function(usr) {
89
            usr.isAlive = false;
90
        });
91
        wss.clients.forEach(function each(ws) {
92
            usersobject.forEach((userobj) => {
93
                if (userobj.websocket === ws) {
94
                    userobj.isAlive = true;
95
                }
96
            });
97
        });
98
        wss.dropdead();
99
    }
100
}, 5000);
101
102
103
// Setup for websocket requests.
104
// Docs: https://github.com/websockets/ws/blob/master/doc/ws.md
105
wss.on("connection", (ws, data) => {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
106
    ws.isAlive = true;
107
    ws.on('pong', heartbeat);
0 ignored issues
show
Bug introduced by
The variable heartbeat seems to be never declared. If this is a global, consider adding a /** global: heartbeat */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
108
109
    console.log("Connection received. Adding client.");
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
110
    ws.on("message", (message) => {
111
        jsonmsg = JSON.parse(message);
0 ignored issues
show
Bug introduced by
The variable jsonmsg seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.jsonmsg.
Loading history...
112
        if (jsonmsg.type === 'newuser') {
113
            var uniquename = gamebrain.uniquifyname(jsonmsg.content);
114
            wss.adduser(uniquename, ws);
115
            playercolor = gamebrain.setPlayerColor(uniquename);
0 ignored issues
show
Bug introduced by
The variable playercolor seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.playercolor.
Loading history...
116
            uniquemsg = {
0 ignored issues
show
Bug introduced by
The variable uniquemsg seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.uniquemsg.
Loading history...
117
                type: "uniquename",
118
                uniquenick: uniquename,
119
                colorclass: playercolor
120
            }
121
            wss.answerBackWith(JSON.stringify(uniquemsg), ws);
122
123
            msg = {
0 ignored issues
show
Bug introduced by
The variable msg seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.msg.
Loading history...
124
                type: "users",
125
                userarray: gamebrain.getPlayersNicks(),
126
                userscolors: gamebrain.getPlayersColors()
127
            }
128
            wss.broadcastUsers(JSON.stringify(msg));
129
        } else if (jsonmsg.type === 'deleteuser') {
130
            wss.dropuser(ws);
131
        } else if (jsonmsg.type === 'clientmsg') {
132
            msg = {
133
                type: "clientmsg",
134
                nick: jsonmsg.nick,
135
                content: jsonmsg.content
136
            }
137
            wss.broadcastUsers(JSON.stringify(msg));
138
        } else if (jsonmsg.type === 'startgame') {
139
            var playerinturn;
140
            gameboard = new Memory.Gameboard(4, 5);
141
            memorycard.placeCards(); // shuffle and place cards on gameboard
142
            playerinturn = gamebrain.setActivePlayer(true); // true for first turn
143
            gameboard.setActivePlayer(playerinturn);
144
            msg = {
145
                type: "startgame",
146
                gameboard: gameboard,
147
                playersturn: playerinturn,
148
                userarray: gamebrain.getPlayersNicks(),
149
                userscolors: gamebrain.getPlayersColors()
150
            }
151
            wss.broadcastUsers(JSON.stringify(msg));
152
        } else if (jsonmsg.type === "clickingcard") {
153
            var position = jsonmsg.x+""+jsonmsg.y;
154
            var cardvalue = memorycard.getCardValue(position);
155
            var type = 'startgame';
156
            var gotpair;
157
            var pairpositions = [];
0 ignored issues
show
Unused Code introduced by
The assignment to variable pairpositions seems to be never used. Consider removing it.
Loading history...
158
159
            gameboard.addPosition(position);
160
            gameboard.addCardValue(cardvalue);
161
162
            // tell gamebrain that move has been done.
163
            gamebrain.makeMove();
164
            // tell gamebrain to remember flipped card and notice eventual pairs
165
            gamebrain.setCardValue(jsonmsg.player, jsonmsg.colorclass, cardvalue);
166
167
168
            if (gamebrain.numberofplayermoves == 2) {
169
                // här har två olika kort vänts.
170
                // spelplanen resettas inte.
171
                // playerinturn sätt så att ingen kan vända kort
172
                playerinturn = false;
173
                gameboard.setActivePlayer(playerinturn);
174
                type = 'turnbackstageone';
175
176
                // msg tillbaka till användaren som gjort klart sitt drag.
177
                // så att denna får fram 'Nästa spelare' knappen
178
                nextbtnmsg = {
0 ignored issues
show
Bug introduced by
The variable nextbtnmsg seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.nextbtnmsg.
Loading history...
179
                    type: 'nextturnbtn'
180
                }
181
                wss.answerBackWith(JSON.stringify(nextbtnmsg), ws);
182
            } else {
183
                // Antingen bara ett kort lyft eller ett par lyft.
184
                // gotpair parametern i gameboard sätt till spelare eller nopair
185
                gotpair = gamebrain.gotPair();
186
                gameboard.setGotPair(gotpair);
187
                playerinturn = gamebrain.setActivePlayer();
188
                gameboard.setActivePlayer(playerinturn);
189
190
                if (gotpair != "") {
191
                    pairpositions = memorycard.getPairPositions(cardvalue);
192
                    gameboard.addPairPositions(pairpositions);
193
                    gameboard.addPairValues(cardvalue);
194
                    gameboard.addPairColors(jsonmsg.colorclass);
195
                }
196
            }
197
198
            msg = {
199
                type: type,
200
                gameboard: gameboard,
201
                playersturn: playerinturn,
202
                userarray: gamebrain.getPlayersNicks(),
203
                userscolors: gamebrain.getPlayersColors(),
204
            }
205
            wss.broadcastUsers(JSON.stringify(msg));
206
        } else if (jsonmsg.type === 'flip') {
207
            // Här har spelaren tryck på 'Nästa spelare'
208
            gameboard.resetCards();
209
            gameboard.setGotPair(gamebrain.gotPair());
210
            playerinturn = gamebrain.setActivePlayer();
211
            gameboard.setActivePlayer(playerinturn);
212
            msg = {
213
                type: 'startgame',
214
                gameboard: gameboard,
215
                playersturn: playerinturn,
216
                userarray: gamebrain.getPlayersNicks(),
217
                userscolors: gamebrain.getPlayersColors(),
218
            }
219
            wss.broadcastUsers(JSON.stringify(msg));
220
        }
221
    });
222
223
    ws.on("error", (error) => {
224
        console.log(`Server error: ${error}`);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
225
    });
226
227
    ws.on("close", (code, reason) => {
228
        console.log(`Closing connection: ${code} ${reason}`);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
229
        msg = {
0 ignored issues
show
Bug introduced by
The variable msg seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.msg.
Loading history...
230
            type: "users",
231
            userarray: gamebrain.getPlayersNicks(),
232
            userscolors: gamebrain.getPlayersColors()
233
        }
234
        wss.broadcastUsers(JSON.stringify(msg));
235
    });
236
});
237