forked from kansalanmol0609/Online-Multiplayer-Chess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
507 lines (439 loc) · 15.4 KB
/
client.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
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
const formEl = document.querySelectorAll('#joinForm > div > input')
const joinButtonEl = document.querySelector('#joinButton')
const messageEl = document.querySelector('#message')
const statusEl = document.querySelector('#status')
const remainingPlayersEl = document.querySelector('#remaining_players')
const ChatEl = document.querySelector('#chat')
const sendButtonEl = document.querySelector('#send')
const roomsListEl = document.getElementById('roomsList');
const myAudioEl = document.getElementById('myAudio');
const singlePlayerEl = document.getElementById('singlePlayer');
const multiPlayerEl = document.getElementById('multiPlayer');
const totalRoomsEl = document.getElementById('rooms')
const totalPlayersEl = document.getElementById('players')
const chatContentEl = document.getElementById('chatContent')
let config = {};
let board = null;
let game = new Chess()
let playerToName = null;
let socketIdToPlayer = null;
function getPlayerId(player) {
if (playerToName == null) {
return `Player ${player}`
} else {
console.assert(player in playerToName)
return playerToName[player]
}
}
// initializing semantic UI dropdown
$('.ui.dropdown')
.dropdown();
// function for defining onchange on dropdown menus
$("#roomDropdown").dropdown({
onChange: function (val) {
console.log(val)
console.log('running the function')
formEl[1].value = val
}
});
function onDragStart(source, piece, position, orientation) {
if (piece[1] != board.player()) return false
}
function makeRandomMove() {
let possibleMoves = game.moves()
// game over
if (possibleMoves.length === 0) {
return false;
}
var randomIdx = Math.floor(Math.random() * possibleMoves.length)
makeMove(possibleMoves[randomIdx])
}
function squareAsArr(square) {
// NOTE for whatever reason, the map is generating a NaN, so we unfold
// it manually below
// move.from = move.from.split('-').map(parseInt);
let arr = square.split('-');
arr[0] = parseInt(arr[0]);
arr[1] = parseInt(arr[1]);
return arr;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function makeMove(move) {
// see if the move is legal
let turn = game.turn()
let move_res = game.move(move)
if (turn != board.player()) {
// don't need to update the board if we're the one who made the move
console.log('updating board position')
board.position(game.currentPosition(), true, move);
}
if (!document.hidden) {
myAudioEl.play().catch(function() {
console.log("couldn't play move tone")
});
}
update();
return move_res
}
function onDropCommon(source, target) {
source = squareAsArr(source);
target = squareAsArr(target);
return makeMove({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
})
}
async function makeCpuMovesSp() {
while (0 in game.remaining_players() && game.turn() !== 0 && !game.game_over()) {
// make random legal move for other players
await sleep(150);
makeRandomMove();
}
}
function onDropSp(source, target) {
if (onDropCommon(source, target) === null) {
// illegal move
return 'snapback'
}
removeGreySquares()
makeCpuMovesSp()
}
const whiteSquareGrey = '#a9a9a9'
const blackSquareGrey = '#696969'
function removeGreySquares () {
$('#myBoard .square-55d63').css('background', '')
}
function greySquare (square) {
var $square = $('#myBoard .square-' + square)
var background = whiteSquareGrey
if ($square.hasClass('black-3c85d')) {
background = blackSquareGrey
}
$square.css('background', background)
}
function onMouseoverSquare(square, piece) {
if (game.turn() != board.player() || piece[1] != board.player()) return
let [row, col] = squareAsArr(square)
let moves = game.moves_single(game.turn(), row, col, /* legal */ true)
// highlight the square they moused over
greySquare(square)
// highlight the possible squares for this piece
for (let i = 0; i < moves.length; i++) {
let [row, col] = moves[i].to
greySquare(row + '-' + col)
}
}
function onMouseoutSquare (square, piece) {
removeGreySquares()
}
singlePlayerEl.addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('gameMode').style.display = "none";
document.querySelector('#chessGame').style.display = null;
document.getElementById('statusPGN').style.display = null
config = {
draggable: true,
position: 'start',
player: 0,
onDragStart: onDragStart,
onDrop: onDropSp,
onMouseoverSquare: onMouseoverSquare,
onMouseoutSquare: onMouseoutSquare,
}
board = Chessboard('myBoard', config);
update()
})
//Connection will be established after webpage is refreshed
const socket = io()
//Triggers after a piece is dropped on the board
function onDropMp(source, target) {
let move = onDropCommon(source, target)
if (move === null) {
// illegal move
return 'snapback'
}
removeGreySquares()
// emits event after piece is dropped
let room = formEl[1].value;
socket.emit('MakeMove', { move, room })
}
socket.on('print', (msg) => {
console.log(msg)
})
function genPlayerImgHtml(player, size='25px', style='') {
return `<img src='img/chesspieces/${player}/k.png' width='${size}' height='${size}' style='margin-left: -2px; margin-right: -2px; ${style}' />`
}
function updateRemainingPlayers(remainingPlayers) {
let remPlayersHtml = remainingPlayers.map(
player => getPlayerId(player) + ' (' + genPlayerImgHtml(player, '25px', 'margin-bottom: -5px;') + ')')
.join(', ');
remainingPlayersEl.innerHTML = remPlayersHtml
}
// set up board
socket.on('SetupBoard', (_socketIdToPlayer, _playerToName) => {
messageEl.textContent = 'Match Started!! Best of Luck...'
playerToName = _playerToName
socketIdToPlayer = _socketIdToPlayer
config.player = socketIdToPlayer[socket.id];
console.log('assigned player id ', config.player)
document.getElementById('joinFormDiv').style.display = "none";
document.querySelector('#chessGame').style.display = null
ChatEl.style.display = null
document.getElementById('statusPGN').style.display = null
board = ChessBoard('myBoard', config)
update()
})
function update() {
let turn = game.turn()
if (turn == board.player()) {
board.set_draggable(true)
} else {
board.set_draggable(false)
}
let res;
if (game.in_check()) {
if (turn == board.player()) {
res = "You are in check!"
}
else {
res = getPlayerId(turn) + " is in check!"
}
res += ' (' + genPlayerImgHtml(turn, '25px', 'margin-bottom: -5px;') + ')';
} else {
if (turn == board.player()) {
res = "Your turn";
}
else {
res = getPlayerId(turn) + "'s turn";
}
res += ' (' + genPlayerImgHtml(turn, '25px', 'margin-bottom: -5px;') + ')';
}
statusEl.innerHTML = res;
updateRemainingPlayers(game.remaining_players())
let players = game.remaining_players()
if (players.length === 1 && players[0] === board.player()) {
alert('You won!')
return false
} else if (players.indexOf(board.player()) === -1) {
alert('You lost!')
return false
} else if (game.in_stalemate()) {
alert('You lost by stalemate!')
return false
}
}
socket.on('MakeMove', (player, move) => {
console.log(`receiving MakeMove (player = ${player}; move = ${move})`)
// if it's this player's turn, then they've already made the move locally
if (player !== board.player()) {
console.assert(makeMove(move))
}
})
//If win or draw
socket.on('gameOver', (turn, win) => {
debugger;
config.draggable = false;
if (win) {
if (turn == board.player()) {
statusEl.innerHTML = "Congratulations, you won!!"
} else {
statusEl.innerHTML = "You lost, better luck next time :)"
}
} else {
statusEl.innerHTML = 'Game Draw'
}
})
//Client disconnected in between
socket.on('disconnectedStatus', (socketId) => {
let player = socketIdToPlayer[socketId]
let name = playerToName[player]
let msg = `Opponent ${name} left the game!!`
alert(msg)
messageEl.textContent = msg
})
//Receiving a message
socket.on('receiveMessage', (user, message) => {
var chatContentEl = document.getElementById('chatContent')
//Create a div element for using bootstrap
chatContentEl.scrollTop = chatContentEl.scrollHeight;
var divEl = document.createElement('div')
if (formEl[0].value == user) {
divEl.classList.add('myMessage');
divEl.textContent = message;
}
else {
divEl.classList.add('youMessage');
divEl.textContent = message;
if (!document.hidden) {
document.getElementById('messageTone').play().catch(function() {
console.log("couldn't play message tone")
});
}
}
var style = window.getComputedStyle(document.getElementById('chatBox'));
if (style.display === 'none') {
document.getElementById('chatBox').style.display = 'block';
}
chatContentEl.appendChild(divEl);
divEl.focus();
divEl.scrollIntoView();
})
//Rooms List update
socket.on('roomsList', (rooms) => {
// roomsListEl.innerHTML = null;
// console.log('Rooms List event triggered!! ', rooms);
totalRoomsEl.innerHTML = rooms.length
var dropRooms = document.getElementById('dropRooms')
while (dropRooms.firstChild) {
dropRooms.removeChild(dropRooms.firstChild)
}
// added event listener to each room
rooms.forEach(x => {
var roomEl = document.createElement('div')
roomEl.setAttribute('class', 'item')
roomEl.setAttribute('data-value', x)
roomEl.textContent = x;
dropRooms.appendChild(roomEl)
})
})
socket.on('updateTotalUsers', totalUsers => {
console.log('total users now', totalUsers)
totalPlayersEl.innerHTML = totalUsers;
})
//Message will be sent only after you click the button
sendButtonEl.addEventListener('click', (e) => {
e.preventDefault()
var message = document.querySelector('#inputMessage').value
var user = formEl[0].value
var room = formEl[1].value
// prepend user name on message
message = user + ': ' + message;
document.querySelector('#inputMessage').value = ''
document.querySelector('#inputMessage').focus()
socket.emit('sendMessage', { user, room, message })
})
//Connect clients only after they click Join
joinButtonEl.addEventListener('click', (e) => {
e.preventDefault()
var user = formEl[0].value, room = formEl[1].value
if (!user || !room) {
messageEl.textContent = "Input fields can't be empty!"
}
else {
joinButtonEl.setAttribute("disabled", "disabled");
formEl[0].setAttribute("disabled", "disabled")
document.querySelector('#roomDropdownP').style.display = 'none';
formEl[1].setAttribute("disabled", "disabled")
//Now Let's try to join it in room // If users more than 2 we will
socket.emit('joinRoom', { user, room }, (error) => {
messageEl.textContent = error
if (alert(error)) {
window.location.reload()
}
else //to reload even if negative confirmation
window.location.reload();
})
messageEl.textContent = "Waiting for other player to join"
}
})
multiPlayerEl.addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('joinFormDiv').style.display = "block";
document.getElementById('gameMode').style.display = "none";
//Server will create a game and clients will play it
//Clients just have to diaplay the game
config = {
draggable: false, //Initially
position: 'start',
onDragStart: onDragStart,
onDrop: onDropMp,
onMouseoverSquare: onMouseoverSquare,
onMouseoutSquare: onMouseoutSquare,
}
// var board = ChessBoard('myBoard', config)
})
// const BLACK_BG = "#E1E1E1"
// const WHITE_BG = "#FFFFFF"
// const BLACK_BG = "#D18B47"
// const WHITE_BG = "#FFCE9E"
// const applyColorScheme = (black, white) => {
// const blackEl = document.querySelectorAll('.black-3c85d');
// for (var i = 0; i < blackEl.length; i++) {
// blackEl[i].style.backgroundColor = BLACK_BG;
// blackEl[i].style.color = WHITE_BG;
// }
// const whiteEl = document.querySelectorAll('.white-1e1d7');
// for (var i = 0; i < whiteEl.length; i++) {
// whiteEl[i].style.backgroundColor = WHITE_BG;
// whiteEl[i].style.color = BLACK_BG;
// }
// }
// applyColorScheme(BLACK_BG, WHITE_BG)
//For removing class from all buttons
const removeClass = () => {
const buttonEl = document.querySelectorAll('.color_b');
for (var i = 0; i < buttonEl.length; i++) {
buttonEl[i].classList.remove('black');
buttonEl[i].classList.remove('grey');
}
}
// // Color Buttons
// document.getElementById('grey_board').addEventListener('click', e => {
// e.preventDefault();
// removeClass();
// document.getElementById('grey_board').classList.add('black');
// document.getElementById('orange_board').classList.add('grey');
// document.getElementById('green_board').classList.add('grey');
// document.getElementById('blue_board').classList.add('grey');
// applyColorScheme("#E1E1E1", "#FFFFFF");
// })
// document.getElementById('orange_board').addEventListener('click', e => {
// e.preventDefault();
// removeClass();
// document.getElementById('grey_board').classList.add('grey');
// document.getElementById('orange_board').classList.add('black');
// document.getElementById('green_board').classList.add('grey');
// document.getElementById('blue_board').classList.add('grey');
// applyColorScheme("#D18B47", "#FFCE9E");
// })
// document.getElementById('green_board').addEventListener('click', e => {
// e.preventDefault();
// removeClass();
// document.getElementById('grey_board').classList.add('grey');
// document.getElementById('orange_board').classList.add('grey');
// document.getElementById('green_board').classList.add('black');
// document.getElementById('blue_board').classList.add('grey');
// applyColorScheme("#58AC8A", "#FFFFFF");
// })
// document.getElementById('blue_board').addEventListener('click', e => {
// e.preventDefault();
// removeClass();
// document.getElementById('grey_board').classList.add('grey');
// document.getElementById('orange_board').classList.add('grey');
// document.getElementById('green_board').classList.add('grey');
// document.getElementById('blue_board').classList.add('black');
// applyColorScheme("#727FA2", "#C3C6BE");
// })
// Messages Modal
document.getElementById('messageBox').addEventListener('click', e => {
e.preventDefault();
var style = window.getComputedStyle(document.getElementById('chatBox'));
if (style.display === 'none') {
document.getElementById('chatBox').style.display = 'block';
} else {
document.getElementById('chatBox').style.display = 'none';
}
})
//
// AUTOMATION
//
// // set player name
// $(formEl[0]).val('ayy' + Math.random().toString().substring(2, 6));
// set room name
$(formEl[1]).val('commit');
// multiPlayerEl.click()
// joinButtonEl.click()
// singlePlayerEl.click()