forked from TheGlobalATeam/moodle-block_chessblock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
530 lines (399 loc) · 13.8 KB
/
main.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
var language = {};
var challengedUserID = -1;
var doingMultiplayer = false;
var enemyPlayerID = -1;
var isPlayer1 = true;
var mpIsMyTyrn = true;
var challengeLookRefreshTime = 1000;
var keepLookingForChallengeResponce = true;
function loadLanguage(Y, currentLanguage) {
language = currentLanguage;
}
//make them globally available, somewhat forward declaration
var onDragStart;
var onDrop;
var onSnapEnd;
var removeHighlight;
var highlightSquare;
var onMouseoverSquare;
var onMouseoutSquare;
var putDownloadLinks;
var updateDownloadLinks;
var makeRandomMove
var updateStatus;
var saveGame;
var board;
var game;
var statusEl;
var gameRunning = false;
$( document ).ready(function() {
game = new Chess();
statusEl = $('#status');
gameRunning = false;
// Do not pick up pieces if the game is over only pick up pieces for the side to move.
onDragStart = function(source, piece, position, orientation) {
if(doingMultiplayer && !mpIsMyTyrn){
return false;
}
if(isPlayer1){
// Only white may move, on their turn.
if (game.in_checkmate() === true ||
game.in_draw() === true ||
piece.search(/^b/) !== -1) {
return false;
}
}else{
// Only white may move, on their turn.
if (game.in_checkmate() === true ||
game.in_draw() === true ||
piece.search(/^w/) !== -1) {
return false;
}
}
};
onDrop = function(source, target) {
removeHighlight();
// See if the move is legal.
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a Queen for example simplicity.
});
// Illegal move.
if (move === null) {
return 'snapback';
}
//my turn over
if(doingMultiplayer){
mpIsMyTyrn = false;
//submit my move to the server!
saveNewFenMP(game.fen());
}
updateStatus();
updateDownloadLinks();
if(!doingMultiplayer){
saveGame();
window.setTimeout(makeRandomMove, 250);
}
};
// Update the board position after the piece snap for castling, en passant, pawn promotion.
onSnapEnd = function() {
board.position(game.fen());
};
removeHighlight = function(square) {
$('#board .square-55d63').css('background', '');
}
highlightSquare = function(square) {
var squareElement = $('#board .square-' + square);
var isSqaureBlack = (squareElement.hasClass('black-3c85d') === true);
var backgroundColor = (isSqaureBlack) ? '#696969' : '#a9a9a9';
squareElement.css('background', backgroundColor);
}
onMouseoverSquare = function(square, piece) {
// Get possible moves for this square.
var moves = game.moves({
square: square,
verbose: true
})
if (moves.length === 0) {
return;
}
//just if my turn
if(doingMultiplayer && !mpIsMyTyrn){
return false;
}
// Highlight hovered square and leagl moves.
highlightSquare(square);
for (var i = 0; i < moves.length; ++i) {
highlightSquare(moves[i].to);
}
}
onMouseoutSquare = function(square, piece) {
removeHighlight();
}
putDownloadLinks = function() {
var fen_link = '<a id="download_fen">' + language['download'] + ' FEN</a>'
var pgn_link = '<a id="download_pgn">' + language['download'] + ' PGN</a>'
$('#download_fen_parent').html(fen_link);
$('#download_pgn_parent').html(pgn_link);
updateDownloadLinks();
}
updateDownloadLinks = function() {
var fen_href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(game.fen());
var result = '*';
if (game.in_draw()) {
result = '1/2-1/2';
}
if (game.in_checkmate()) {
result = game.turn() === 'b' ? '1-0' : '0-1';
}
var pgn_data = '[White "Human"]\n[Black "Moodle computer"]\n[Result "' + result + '"]\n' + game.pgn();
var pgn_href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(pgn_data);
$('#download_fen').attr('href', fen_href).attr('download', 'fen.fen');
$('#download_pgn').attr('href', pgn_href).attr('download', 'pgn.pgn');
}
makeRandomMove = function() {
var possibleMoves = game.moves();
// Game over.
if (possibleMoves.length === 0) {
return;
}
var randomIndex = Math.floor(Math.random() * possibleMoves.length);
game.move(possibleMoves[randomIndex]);
board.position(game.fen());
updateStatus();
updateDownloadLinks();
saveGame();
};
updateStatus = function() {
var status = '';
var moveColor = (game.turn() === 'b') ? language['black'] : language['white'];
if (game.in_checkmate() === true) {
status = language['gameover'] + ', ' + moveColor + ' ' + language['isincheckmate'];
} else if (game.in_draw() == true) {
status = language['gameover'] + ', ' + language['drawnposition'];
} else {
status = moveColor + ' ' + language['tomove'];
if (game.in_check() === true) {
status += ', ' + moveColor + ' ' + language['isincheck'];
}
}
statusEl.html(status);
};
saveGame = function(){
if(!gameRunning){
console.log("need to start a game in order to save");
return;
}
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/post_game_data.php", {
method: "POST",
data: 'gameFEN=' + game.fen() + '&gamePGN=NOPE',
on: {
success: function(io, o, arguments) {
//console.log("SAVED!");
}
}
}
);
}
updateStatus();
$('#newChessGame').click(function(){
startChessGame();
});
$('#loadPrevChessGame').click(function(){
$('#loadPrevChessGame').hide();
// Loading from API.
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/get_game_data.php", {
method: "GET",
on: {
success: function(io, o, arguments) {
var gameData = JSON.parse(o.response);
if (gameData.status && gameData.gameData.game_fen != null && gameData.gameData.game_fen.length > 0){
var cfgLoad = $.extend({}, cfg); // Copy configuration.
cfgLoad.position = gameData.gameData.game_fen;
game = new Chess(gameData.gameData.game_fen);
board = new ChessBoard('board', cfgLoad);
$(window).resize(board.resize);
gameRunning = true;
}
}
}
}
);
});
$('#openMultiplayer').click(function(){
// $('#loadPrevChessGame').hide();
// $('#loadPrevChessGame').hide();
// Loading from API.
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/get_online_users.php", {
method: "GET",
on: {
success: function(io, o, arguments) {
var gameData = JSON.parse(o.response);
let dataContent = "<p>Select player to challenge:</p>";
for(let i = 0; i < gameData.userList.length; i ++){
//console.dir(gameData.userList[i].id);
dataContent += '<br><button onclick="challengePlayerByID('+gameData.userList[i].id+')">Challenge '+gameData.userList[i].username+'</button>';
}
$('#onlineUsersListContainer').html(dataContent);
}
}
}
);
});
});
function startChessGame(usingFen = false){
var chessCfg = {
draggable: true,
orientation: 'white',
position: 'start',
onDragStart: onDragStart,
onMouseoutSquare: onMouseoutSquare,
onMouseoverSquare: onMouseoverSquare,
onDrop: onDrop,
onSnapEnd: onSnapEnd,
pieceTheme: M.cfg.wwwroot + '/blocks/chessblock/chessboardjs/img/chesspieces/wikipedia/{piece}.png',
};
if(usingFen != false){
console.log("using pos");
chessCfg.position = usingFen
}
if(doingMultiplayer){
if(isPlayer1){
chessCfg.orientation = 'white';
}else{
chessCfg.orientation = 'black';
}
}
board = new ChessBoard('board', chessCfg);
//console.log(board.fen());
if(usingFen != false){
game = new Chess(usingFen);
}else{
game = new Chess();
}
//console.log(game.fen());
$('#loadPrevChessGame').hide();
gameRunning = true;
updateStatus();
$(window).resize(board.resize);
putDownloadLinks();
}
function challengePlayerByID(playerID){ //TDO add username here
$('#loadingDiv').show();
$('#buttonsContainer').hide();
$('#gameInfoCointainer').hide();
$('#onlineUsersListContainer').html("<p>Loading</p>");
challengedUserID = playerID;
enemyPlayerID = playerID;
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/post_chess_challenge.php", {
method: "POST",
data: 'challengedUserID=' + playerID ,
on: {
success: function(io, o, arguments) {
var challengeResponce = JSON.parse(o.response);
// console.dir(challengeResponce);
// console.log("SAVED!");
$('#onlineUsersListContainer').html("<p>You have challenged "+playerID+"</p>");
lookForResponce();
}
}
}
);
console.log("I challenge: " + playerID);
}
function lookForResponce(){
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/chess_challenge_status.php?challengedUserID="+challengedUserID, {
method: "GET",
on: {
success: function(io, o, arguments) {
var gameData = JSON.parse(o.response);
// console.log("responce lookForResponce");
// console.dir(gameData);
if (gameData.status){
if (gameData.challengeAccepted){
keepLookingForChallengeResponce = false;
startMultiplayerMatch(true);
}
}
}
}
}
);
if(keepLookingForChallengeResponce){
setTimeout(lookForResponce, challengeLookRefreshTime);
}
}
//also called by multiplayerNotificatin by player 2
function startMultiplayerMatch(isFirstPlayer){
//safequard against race condition as only the first call will be accepted
if(doingMultiplayer){
return;
}
doingMultiplayer = true;
keepLookingForChallenge = false;
isPlayer1 = isFirstPlayer;
if(isFirstPlayer){
$('#loadingDiv').hide();
$('#buttonsContainer').show();
$('#gameInfoCointainer').show();
$('#onlineUsersListContainer').html("<p>In multiplayer</p>");
console.log("Starting MP FirstPlayer");
}else{
mpIsMyTyrn = false;
console.log("Starting MP SecoundPlayer");
//TODO start looking for other players move
}
startChessGame();
lookForOtherPlayersMoves();
}
function saveNewFenMP(fen){
var isPlayer1Number = 1;
if(!isPlayer1){
isPlayer1Number = 0;
}
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/chess_mp_moves.php?isPlayer1="+isPlayer1Number+"&otherPlayerID="+enemyPlayerID, {
method: "POST",
data: 'newFen=' + fen,
on: {
success: function(io, o, arguments) {
//console.log(o.response);
var responce = JSON.parse(o.response);
//console.dir(responce);
if(responce.status){
//console.log("SAVED!");
}
}
}
}
);
}
function lookForOtherPlayersMoves(){
var isPlayer1Number = 1;
if(!isPlayer1){
isPlayer1Number = 0;
}
Y.io(
M.cfg.wwwroot + "/blocks/chessblock/api/chess_mp_moves.php?isPlayer1="+isPlayer1Number+"&otherPlayerID="+enemyPlayerID, {
method: "GET",
on: {
success: function(io, o, arguments) {
var returnJson = JSON.parse(o.response);
if (returnJson.status){
if(returnJson.gameData.game_fen != game.fen()){
//new fen!
var oldFen = game.fen();
var newFen = returnJson.gameData.game_fen;
mpIsMyTyrn = true;
startChessGame(newFen);
addYourTurnNotification();
}
}
}
}
}
);
setTimeout(lookForOtherPlayersMoves, challengeLookRefreshTime);
}
function addYourTurnNotification(){
if (!canUseNotifications) {
return;
}
var options = {
body: "Your opponent have made a move!",
icon: M.cfg.wwwroot + "/blocks/chessblock/Chess-Game.png",
tag: "#LiveToWin"
}
var title = "Your turn!";
var notification = new Notification(title, options);
notification.onclick = function() {
notification.close();
console.log("Clicked!");
}
}