-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1514 lines (1360 loc) · 76.4 KB
/
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
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Chess</title>
<!-- Import Supabase Client Library -->
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
margin: 10px 0;
padding: 0;
}
.hidden { display: none !important; }
#mode-selection, #friend-setup, #waiting-screen, #game-area {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 20px;
text-align: center;
width: 90%;
max-width: 550px;
}
button, input[type="text"] {
padding: 10px 15px;
font-size: 0.95em;
margin: 5px;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 5px;
}
/* General button styling (not for squares) */
#mode-selection button, #friend-setup button, #waiting-screen button, #game-area > button#resetButton {
background-color: #4CAF50;
color: white;
border: none;
min-width: 100px;
}
#mode-selection button:hover, #friend-setup button:hover, #waiting-screen button:hover, #game-area > button#resetButton:hover {
background-color: #45a049;
}
#mode-selection button:disabled, #friend-setup button:disabled, #waiting-screen button:disabled, #game-area > button#resetButton:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
input[type="text"] {
width: 80%;
max-width: 250px;
}
#share-link-area {
margin-top: 15px;
padding: 10px;
background-color: #e9e9e9;
border: 1px dashed #ccc;
border-radius: 4px;
word-break: break-all;
width: 95%;
box-sizing: border-box;
display: flex;
align-items: center;
}
#share-link-area input {
flex-grow: 1;
margin-bottom: 0;
margin-right: 5px;
box-sizing: border-box;
}
#share-link-area button { /* Specific style for copy button */
flex-shrink: 0;
width: 100px;
background-color: #555; /* Different color for copy button */
color: white;
border: none;
}
#share-link-area button:hover {
background-color: #777;
}
/* --- Chessboard and Piece Styling --- */
#board-container {
display: grid;
grid-template-areas:
". top ."
"left board right"
". bottom .";
grid-template-columns: auto 1fr auto;
grid-template-rows: auto 1fr auto;
gap: 3px;
margin-top: 10px;
max-width: 100%;
}
:root {
--board-size: min(80vw, 440px);
--square-size: calc(var(--board-size) / 8);
--piece-size: calc(var(--square-size) * 0.7);
--label-size: calc(var(--square-size) * 0.6);
--border-width: max(2px, calc(var(--square-size) * 0.05));
}
.labels { display: flex; justify-content: center; align-items: center; font-weight: bold; color: #555; font-size: calc(var(--label-size) * 0.8); }
.labels.files { flex-direction: row; height: var(--label-size); }
.labels.ranks { flex-direction: column; width: var(--label-size); }
.label { width: var(--square-size); height: var(--square-size); display: flex; justify-content: center; align-items: center; box-sizing: border-box;}
#top-files { grid-area: top; }
#bottom-files { grid-area: bottom; }
#left-ranks { grid-area: left; }
#right-ranks { grid-area: right; }
#chessboard {
grid-area: board;
width: var(--board-size);
height: var(--board-size);
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-template-rows: repeat(8, 1fr);
border: var(--border-width) solid #333;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
/* == Base styles for BOTH div and button squares == */
.square-base {
width: 100%; /* Fill grid cell */
height: 100%; /* Fill grid cell */
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box; /* Include padding/border in size */
position: relative;
border: none; /* Remove border */
padding: 0; /* Remove padding */
margin: 0; /* Remove margin */
vertical-align: top; /* Consistent vertical alignment */
/* Make the actual text (notation) visually hidden but accessible */
font-size: 1px;
color: transparent;
overflow: hidden; /* Hide any potential overflow */
/* Ensure consistent font for layout calculation */
font-family: sans-serif;
line-height: normal; /* Reset line height */
text-align: center; /* Consistent alignment */
}
/* == Button-specific resets and styles == */
.square-button {
cursor: pointer;
transition: background-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out, filter 0.1s ease-in-out;
/* Explicit resets to counter browser defaults */
background: transparent; /* Override default button background */
-webkit-appearance: none; /* Remove OS styling */
-moz-appearance: none;
appearance: none;
/* Ensure properties match .square-base in case of specificity issues */
border: none;
padding: 0;
margin: 0;
font-size: 1px;
color: transparent;
font-family: inherit; /* Inherit from body/parent */
line-height: normal;
text-align: center;
}
.square-button:hover {
filter: brightness(1.1); /* Use filter for hover effect */
}
/* == Div-specific styles (Minimal) == */
.square-div {
cursor: default;
background-color: transparent; /* Ensure transparent background */
}
/* == Background colors for light/dark squares (applied AFTER resets) == */
.square-base.light { background-color: #f0d9b5; }
.square-base.dark { background-color: #b58863; }
/* == Piece color and pseudo-element for symbol == */
.square-base.white { color: #ffffff; text-shadow: 1px 1px 2px #000000; }
.square-base.black { color: #000000; text-shadow: 1px 1px 2px #aaaaaa;}
/* Use ::before to display the piece symbol */
.square-base.has-piece::before {
content: attr(data-piece-symbol); /* Get symbol from data attribute */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: var(--piece-size); /* Use variable for piece size */
color: inherit; /* Inherit color from .white/.black class */
text-shadow: inherit; /* Inherit shadow from .white/.black class */
pointer-events: none; /* Don't interfere with clicks */
line-height: 1; /* Prevent line height from affecting position */
}
/* --- Interaction State Classes (applied ONLY to buttons) --- */
.square-button.selected {
/* Inset shadow doesn't affect layout size */
box-shadow: inset 0 0 0 var(--border-width) rgba(0, 150, 0, 0.8);
}
.square-button.valid-move::after {
/* Pseudo-element for dot, doesn't affect layout */
content: '';
position: absolute;
width: 25%;
height: 25%;
background-color: rgba(0, 0, 0, 0.25);
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
.square-button.capture-move {
/* Outline doesn't affect layout size */
outline: var(--border-width) dashed rgba(200, 0, 0, 0.7);
outline-offset: calc(-1 * var(--border-width)); /* Draw outline inside */
}
#status {
margin-top: 10px;
font-size: 1.1em;
font-weight: bold;
min-height: 1.4em;
color: #333;
}
#info-area {
margin-top: 5px;
font-size: 0.9em;
color: #666;
min-height: 1.2em;
}
</style>
</head>
<body>
<h1>Web Chess</h1>
<!-- 1. Mode Selection -->
<div id="mode-selection">
<h2>Choose Game Mode</h2>
<button id="selfPlayButton">Self-play</button>
<button id="friendPlayButton">Play with Human</button>
</div>
<!-- 2. Friend Mode Setup -->
<div id="friend-setup" class="hidden">
<h2>Play with Human</h2>
<input type="text" id="player1NameInput" placeholder="Enter your name (Player 1 - White)">
<button id="createGameButton">Create Game & Get Link</button>
<button id="backToModeSelectionButton1">Back</button>
</div>
<!-- 3. Waiting Screen (Friend Mode) -->
<div id="waiting-screen" class="hidden">
<h2>Waiting for Human...</h2>
<p>Share this link with your human:</p>
<div id="share-link-area">
<input type="text" id="shareLinkInput" readonly>
<button id="copyLinkButton">Copy Link</button>
</div>
<p id="waiting-message">Initializing...</p>
<button id="cancelGameButton">Cancel Game</button>
</div>
<!-- 4. Game Area (Both Modes) -->
<div id="game-area" class="hidden">
<div id="status">White's turn</div>
<div id="info-area"></div> <!-- For player names or messages -->
<div id="board-container">
<div id="top-files" class="labels files"></div>
<div id="left-ranks" class="labels ranks"></div>
<div id="chessboard"></div>
<div id="right-ranks" class="labels ranks"></div>
<div id="bottom-files" class="labels files"></div>
</div>
<button id="resetButton">Reset Game</button> <!-- Only works in Self-Play -->
</div>
<script>
// --- DOM Elements ---
const modeSelectionDiv = document.getElementById('mode-selection');
const friendSetupDiv = document.getElementById('friend-setup');
const waitingScreenDiv = document.getElementById('waiting-screen');
const gameAreaDiv = document.getElementById('game-area');
const selfPlayButton = document.getElementById('selfPlayButton');
const friendPlayButton = document.getElementById('friendPlayButton');
const player1NameInput = document.getElementById('player1NameInput');
const createGameButton = document.getElementById('createGameButton');
const backToModeSelectionButton1 = document.getElementById('backToModeSelectionButton1');
const shareLinkInput = document.getElementById('shareLinkInput');
const copyLinkButton = document.getElementById('copyLinkButton');
const waitingMessage = document.getElementById('waiting-message');
const cancelGameButton = document.getElementById('cancelGameButton');
const chessboardElement = document.getElementById('chessboard');
const statusElement = document.getElementById('status');
const infoElement = document.getElementById('info-area');
const resetButton = document.getElementById('resetButton');
const topFilesLabel = document.getElementById('top-files');
const bottomFilesLabel = document.getElementById('bottom-files');
const leftRanksLabel = document.getElementById('left-ranks');
const rightRanksLabel = document.getElementById('right-ranks');
// --- Supabase Config ---
// IMPORTANT: Replace with your actual Supabase URL and Anon Key
const SUPABASE_URL = 'https://knjmvosajcdmfqffkzcb.supabase.co'; // Use your URL
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imtuam12b3NhamNkbWZxZmZremNiIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDUzMjg5NDgsImV4cCI6MjA2MDkwNDk0OH0.Ii6VAM9KiaG2urHinrUfFmSP_YBXA7l-O5l__Q9CPUI'; // Use your Anon Key
const supabaseClient = supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
// --- Game Constants ---
const PIECES = {
'P': { type: 'pawn', color: 'white', unicode: '♙' },
'R': { type: 'rook', color: 'white', unicode: '♖' },
'N': { type: 'knight', color: 'white', unicode: '♘' },
'B': { type: 'bishop', color: 'white', unicode: '♗' },
'Q': { type: 'queen', color: 'white', unicode: '♕' },
'K': { type: 'king', color: 'white', unicode: '♔' },
'p': { type: 'pawn', color: 'black', unicode: '♟' },
'r': { type: 'rook', color: 'black', unicode: '♜' },
'n': { type: 'knight', color: 'black', unicode: '♞' },
'b': { type: 'bishop', color: 'black', unicode: '♝' },
'q': { type: 'queen', color: 'black', unicode: '♛' },
'k': { type: 'king', color: 'black', unicode: '♚' }
};
const initialBoardSimple = [
['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
[null, null, null, null, null, null, null, null],
[null, null, null, null, null, null, null, null],
[null, null, null, null, null, null, null, null],
[null, null, null, null, null, null, null, null],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
];
const initialCastlingRights = { white: { kingSide: true, queenSide: true }, black: { kingSide: true, queenSide: true } };
// --- Game State ---
let gameMode = null; // 'self' or 'friend'
let board = []; // The 8x8 board with piece objects or null
let currentPlayer = 'white';
let selectedPiece = null; // { piece, row, col }
let validMoves = []; // Array of { row, col } for the selected piece
let initialClickablePieces = []; // Array of {row, col} for pieces clickable at turn start
let gameOver = false; // Or status string like "Checkmate! ..."
let checkStatus = { white: false, black: false };
let castlingRights = JSON.parse(JSON.stringify(initialCastlingRights)); // Deep copy
let enPassantTarget = null; // { row, col } or null
// --- Friend Mode State ---
let currentGameId = null;
let playerColor = null; // 'white' or 'black' (assigned in friend mode)
let player1Name = '';
let player2Name = '';
let gameSubscription = null;
let isMyTurn = false; // Derived from currentPlayer and playerColor
// --- Initialization ---
function initGame(initialState = null) {
console.log(`%cinitGame called. Mode: ${gameMode}`, 'color: blue; font-weight: bold;', "Initial State:", initialState);
// --- Reset Local State Section ---
selectedPiece = null;
validMoves = [];
initialClickablePieces = [];
checkStatus = { white: false, black: false };
// Keep existing player names/color if loading from state, otherwise reset
if (!initialState) {
player1Name = 'Player 1';
player2Name = 'Player 2';
playerColor = 'white';
isMyTurn = true;
castlingRights = JSON.parse(JSON.stringify(initialCastlingRights)); // Reset castling rights
enPassantTarget = null; // Reset en passant
}
// --- End Reset ---
if (gameMode === 'self' || !initialState) {
console.log("initGame: Setting up for Self-Play or initial Friend state.");
board = deserializeBoard(initialBoardSimple);
currentPlayer = 'white';
// Reset castling/enpassant if not already done (e.g., self-play start)
if(!initialState) {
castlingRights = JSON.parse(JSON.stringify(initialCastlingRights));
enPassantTarget = null;
}
gameOver = false;
infoElement.textContent = ''; // Clear names initially for self-play
} else if (gameMode === 'friend' && initialState) {
console.log("initGame: Loading state from Supabase for Friend mode.");
board = deserializeBoard(initialState.board_state);
currentPlayer = initialState.current_turn;
// Ensure castling rights are valid objects, default if null/malformed
castlingRights = (initialState.castling_rights && typeof initialState.castling_rights === 'object')
? initialState.castling_rights
: JSON.parse(JSON.stringify(initialCastlingRights));
enPassantTarget = initialState.en_passant_target; // Supabase stores JSON directly
player1Name = initialState.player_white_name || 'White';
// IMPORTANT: Update local player2Name here
player2Name = initialState.player_black_name || (playerColor === 'black' ? '(You - Black)' : 'Black');
gameOver = determineGameOverStatus(initialState.game_status, initialState.winner);
currentGameId = initialState.id; // Ensure game ID is consistent
console.log(`initGame: Loaded P1=${player1Name}, P2=${player2Name}, Turn=${currentPlayer}, Status=${initialState.game_status}`);
}
// Disable reset button in friend mode
resetButton.disabled = (gameMode === 'friend');
// Ensure UI state is correct *unconditionally* when entering game screen
console.log("initGame: Updating UI visibility.");
modeSelectionDiv.classList.add('hidden');
friendSetupDiv.classList.add('hidden');
waitingScreenDiv.classList.add('hidden'); // <-- Ensure waiting screen is hidden
gameAreaDiv.classList.remove('hidden'); // <-- Ensure game area is shown
createLabels(); // Create/update board labels
prepareTurn(); // Calculate initial turn state, check game end, render
}
// --- UI Navigation ---
function showModeSelection() {
modeSelectionDiv.classList.remove('hidden');
friendSetupDiv.classList.add('hidden');
waitingScreenDiv.classList.add('hidden');
gameAreaDiv.classList.add('hidden');
cleanupSubscription();
resetLocalGameState();
document.title = "Web Chess"; // Reset title
}
function showFriendSetup() {
modeSelectionDiv.classList.add('hidden');
friendSetupDiv.classList.remove('hidden');
waitingScreenDiv.classList.add('hidden');
gameAreaDiv.classList.add('hidden');
}
function showWaitingScreen(gameId, p1Name) {
modeSelectionDiv.classList.add('hidden');
friendSetupDiv.classList.add('hidden');
waitingScreenDiv.classList.remove('hidden');
gameAreaDiv.classList.add('hidden');
const link = `${window.location.origin}${window.location.pathname}#gameId=${gameId}`;
shareLinkInput.value = link;
waitingMessage.textContent = `Game created by ${p1Name}. Waiting for opponent...`;
currentGameId = gameId;
document.title = "Web Chess - Waiting...";
}
function resetLocalGameState() {
gameMode = null;
board = [];
currentPlayer = 'white';
selectedPiece = null;
validMoves = [];
initialClickablePieces = [];
gameOver = false;
checkStatus = { white: false, black: false };
castlingRights = JSON.parse(JSON.stringify(initialCastlingRights));
enPassantTarget = null;
currentGameId = null;
playerColor = null;
player1Name = '';
player2Name = '';
gameSubscription = null;
isMyTurn = false;
statusElement.textContent = "White's turn";
infoElement.textContent = "";
chessboardElement.innerHTML = ''; // Clear board visually
}
// --- Board Representation Helpers ---
function serializeBoard(boardWithObjs) {
// Convert board with piece objects back to simple identifiers for Supabase
return boardWithObjs.map(row =>
row.map(piece => {
if (!piece) return null;
// Find the key ('P', 'r', etc.) corresponding to the piece object
return Object.keys(PIECES).find(key =>
PIECES[key].type === piece.type && PIECES[key].color === piece.color
) || null;
})
);
}
function deserializeBoard(boardSimple) {
// Convert simple board identifiers from Supabase to board with piece objects
if (!boardSimple || !Array.isArray(boardSimple)) {
console.error("Invalid simple board data for deserialization:", boardSimple);
// Return default initial board if data is bad
return initialBoardSimple.map(row => row.map(p => p ? { ...PIECES[p] } : null));
}
return boardSimple.map(row =>
row.map(pieceKey => pieceKey ? { ...PIECES[pieceKey] } : null)
);
}
// --- Supabase Interaction ---
async function createSupabaseGame() {
player1Name = player1NameInput.value.trim() || 'Player 1 (White)';
if (!player1Name) {
alert("Please enter your name.");
return;
}
createGameButton.disabled = true; createGameButton.textContent = 'Creating...';
try {
// Use supabaseClient
const { data, error } = await supabaseClient
.from('chess_games')
.insert({
player_white_name: player1Name,
// Explicitly set initial state in DB on creation
board_state: initialBoardSimple,
current_turn: 'white',
castling_rights: initialCastlingRights,
en_passant_target: null,
game_status: 'waiting'
})
.select()
.single();
if (error) throw error;
if (data) {
console.log("Game created in DB:", data);
gameMode = 'friend';
playerColor = 'white'; // Creator is White
currentGameId = data.id;
player1Name = data.player_white_name; // Use name returned from DB
showWaitingScreen(data.id, player1Name);
startListeningForGameUpdates(data.id);
} else {
alert("Failed to create game. No data returned.");
// Don't disable button permanently on this type of error
// createGameButton.disabled = false;
}
} catch (error) {
console.error("Error creating game:", error);
alert(`Error creating game: ${error.message}`);
// createGameButton.disabled = false; // Don't disable button permanently
}
finally {
// Ensure button is re-enabled and text reset regardless of success/error
createGameButton.disabled = false;
createGameButton.textContent = 'Create Game & Get Link';
}
}
async function joinSupabaseGame(gameId) {
console.log("Attempting to join game:", gameId);
try {
// Use supabaseClient
const { data: gameData, error: fetchError } = await supabaseClient
.from('chess_games')
.select('*').eq('id', gameId).single();
if (fetchError || !gameData) { throw fetchError || new Error("Game not found."); }
console.log("Found game:", gameData);
// Handle rejoining or joining waiting game
if (gameData.game_status === 'active') {
// Rejoining logic (simplified)
alert(`Game already active between ${gameData.player_white_name} and ${gameData.player_black_name}. Loading game state.`);
if (!gameData.player_white_name || !gameData.player_black_name) {
alert("Error: Active game is missing player names."); showModeSelection(); return;
}
// Determine player color based on loaded names - assume user is one of them
playerColor = null; // Will be determined implicitly or explicitly later if needed
gameMode = 'friend';
currentGameId = gameId;
initGame(gameData); // Load the existing active game state
startListeningForGameUpdates(gameId);
return;
} else if (gameData.game_status === 'waiting') {
// Join as Black
player2Name = prompt(`Joining game created by ${gameData.player_white_name}.\nEnter your name (Player 2 - Black):`, "Player 2 (Black)");
if (!player2Name || !player2Name.trim()) { alert("You must enter a name."); return; }
player2Name = player2Name.trim();
// Use supabaseClient
const { data: updateData, error: updateError } = await supabaseClient
.from('chess_games')
.update({ player_black_name: player2Name, game_status: 'active' })
.eq('id', gameId)
.select().single();
if (updateError) throw updateError;
console.log("Game joined and updated:", updateData);
gameMode = 'friend';
playerColor = 'black'; // Joiner is Black
currentGameId = gameId;
initGame(updateData); // Load the initial active game state
startListeningForGameUpdates(gameId); // Start listening *after* successful join
} else { // Game finished or aborted
alert(`Cannot join game. Status: ${gameData.game_status}`);
showModeSelection(); return;
}
} catch (error) {
console.error("Error joining game:", error);
alert(`Error joining game: ${error.message}`);
showModeSelection(); // Go back on error
}
}
async function sendMoveToSupabase(fromRow, fromCol, toRow, toCol, promotionPiece = null) {
if (gameMode !== 'friend' || !currentGameId || !isMyTurn) { // Guard clause
console.warn("Attempted to send move when not allowed.");
return;
}
console.log(`%cSending move: ${getNotation(fromRow, fromCol)}->${getNotation(toRow, toCol)}`, 'color: green');
// Temporarily disable further interaction locally
isMyTurn = false; // Mark as not my turn anymore locally
chessboardElement.removeEventListener('click', handleSquareClick);
// Optionally re-render immediately to remove interaction highlights
// renderBoard();
// Make move locally to calculate next state
const moveResult = makeMove(fromRow, fromCol, toRow, toCol, promotionPiece);
if (!moveResult) {
console.error("Local move failed before sending! Attempting to restore state.");
isMyTurn = true; // Re-enable (might cause issues if state is truly broken)
prepareTurn(); // Refresh UI based on potentially corrupted state
alert("An error occurred processing the move locally. Game might be out of sync.");
return;
}
// Calculate next state variables *after* local move
const nextPlayer = (currentPlayer === 'white') ? 'black' : 'white';
const simpleBoard = serializeBoard(board);
const currentEnPassantTarget = enPassantTarget;
const currentCastlingRights = castlingRights;
// Determine game end state based on *next* player's possibilities
let nextGameStatus = 'active';
let winner = null;
const opponentColor = nextPlayer;
const opponentKingInCheck = isKingInCheck(opponentColor, board); // Check opponent AFTER move
const opponentHasMoves = findClickablePiecesForPlayer(opponentColor, board, currentCastlingRights, currentEnPassantTarget).length > 0;
if (!opponentHasMoves) {
if (opponentKingInCheck) { // Checkmate
winner = currentPlayer; // The player who just moved wins
nextGameStatus = `checkmate_${winner}`;
gameOver = `Checkmate! ${winner === 'white' ? player1Name : player2Name} wins.`; // Set local game over message
} else { // Stalemate
winner = 'draw';
nextGameStatus = 'stalemate';
gameOver = "Stalemate! It's a draw."; // Set local game over message
}
console.log(`%cGame Over calculated by sender: ${nextGameStatus}`, 'color: red; font-weight: bold');
}
// Update Supabase - Use supabaseClient
try {
const { error } = await supabaseClient
.from('chess_games')
.update({
board_state: simpleBoard,
current_turn: nextPlayer,
en_passant_target: currentEnPassantTarget,
castling_rights: currentCastlingRights,
last_move_from: getNotation(fromRow, fromCol),
last_move_to: getNotation(toRow, toCol),
game_status: nextGameStatus,
winner: winner
})
.eq('id', currentGameId);
if (error) { throw error; }
console.log("Move sent to Supabase successfully.");
// Local state updated via subscription handler now
} catch (error) {
console.error("Error updating game state:", error);
alert(`Error sending move: ${error.message}. Game might be out of sync. Please refresh.`);
}
}
async function cancelSupabaseGame() {
if (!currentGameId) return;
const confirmation = confirm("Are you sure you want to cancel this game? This cannot be undone.");
if (!confirmation) return;
cleanupSubscription(); // Stop listening first
try {
// Use supabaseClient
const { error } = await supabaseClient
.from('chess_games')
.update({ game_status: 'aborted', winner: 'none' }) // Mark as aborted
.eq('id', currentGameId);
if (error) throw error;
console.log("Game cancelled/aborted in database.");
alert("Game cancelled.");
showModeSelection(); // Go back to start screen
} catch (error) {
console.error("Error cancelling game:", error);
alert(`Error cancelling game: ${error.message}`);
showModeSelection(); // Still go back
}
}
function startListeningForGameUpdates(gameId) {
cleanupSubscription();
console.log(`%cAttempting to subscribe to game: ${gameId}`, 'color: purple');
if (!gameId) { console.error("Cannot subscribe, gameId is null!"); return; }
// Use supabaseClient
gameSubscription = supabaseClient.channel(`chess_game_${gameId}`)
.on('postgres_changes',
{ event: 'UPDATE', schema: 'public', table: 'chess_games', filter: `id=eq.${gameId}` },
payload => {
console.log(`%cReceived RAW update via subscription for ${gameId}:`, 'color: orange', payload.new);
// Add a small delay before handling update to mitigate potential race conditions?
// setTimeout(() => handleGameUpdate(payload.new), 50);
handleGameUpdate(payload.new); // Pass the new record data
}
)
.subscribe((status, err) => {
console.log(`%cSubscription status for ${gameId}: ${status}`, 'color: purple', err || '');
if (status === 'SUBSCRIBED') {
console.log('%cSuccessfully subscribed!', 'color: green; font-weight: bold');
} else if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT' || status === 'CLOSED') {
console.error('Subscription error/closed:', status, err);
if (!document.hidden) {
alert("Realtime connection issue. Game updates may be delayed. Please refresh if problems persist.");
}
cleanupSubscription();
}
});
}
function cleanupSubscription() {
if (gameSubscription) {
console.log("Removing previous game subscription.");
// Use supabaseClient
supabaseClient.removeChannel(gameSubscription)
.then(status => console.log("Subscription remove status:", status))
.catch(error => console.error("Error removing subscription:", error));
gameSubscription = null;
}
}
// --- Refined Update Handler ---
function handleGameUpdate(newState) {
console.log(`%chandleGameUpdate called. Current local mode=${gameMode}, color=${playerColor}.`, 'color: orange');
console.log("Received newState:", newState);
// Guard: Only process updates in friend mode
if (gameMode !== 'friend') {
console.log("handleGameUpdate: Skipping, not in friend mode.");
return;
}
// Guard: Check if gameId matches current game
if (!currentGameId || newState.id !== currentGameId) {
console.log("handleGameUpdate: Skipping, update is for a different game ID.");
return;
}
// **Scenario 1: Player 1 is waiting and Player 2 joins**
// Check if the waiting screen is currently visible for this client
const isWaitingScreenVisible = !waitingScreenDiv.classList.contains('hidden');
if (isWaitingScreenVisible && playerColor === 'white' && newState.game_status === 'active' && newState.player_black_name) {
console.log(`%cDETECTED P2 JOIN! (P1 perspective). Initializing game screen...`, 'color: green; font-weight: bold');
// Update local player 2 name *before* initializing game
player2Name = newState.player_black_name;
// Call initGame to load the full state and switch UI
initGame(newState);
return; // Stop further processing for this specific update
}
// **Scenario 2: Update during an active or finished game**
// Check if the game area is currently visible
const isGameAreaVisible = !gameAreaDiv.classList.contains('hidden');
if (isGameAreaVisible && newState.game_status !== 'waiting') {
console.log("handleGameUpdate: Processing update for active/finished game.");
// --- Check for stale updates (optional but can help) ---
// If this update seems older than the current local state (e.g., based on turn number or move count if implemented)
// you could potentially ignore it. For simplicity, we process all updates for now.
// Update local state from the received data
board = deserializeBoard(newState.board_state);
currentPlayer = newState.current_turn;
castlingRights = (newState.castling_rights && typeof newState.castling_rights === 'object')
? newState.castling_rights
: JSON.parse(JSON.stringify(initialCastlingRights));
enPassantTarget = newState.en_passant_target;
player1Name = newState.player_white_name || 'White';
player2Name = newState.player_black_name || 'Black'; // Keep P2 name updated
gameOver = determineGameOverStatus(newState.game_status, newState.winner);
console.log(`handleGameUpdate: Local state updated. Turn=${currentPlayer}, Status=${newState.game_status}, GameOver=${gameOver}`);
// Re-calculate turn logic and re-render the board
// PrepareTurn handles setting isMyTurn and adding/removing listeners
prepareTurn();
} else {
console.log("handleGameUpdate: Skipping update - conditions not met (game area hidden, or status is 'waiting' and not the P2 join trigger).");
}
}
function determineGameOverStatus(status, winner) {
const p1 = player1Name || 'White';
const p2 = player2Name || 'Black';
switch (status) {
case 'checkmate_white': return `Checkmate! ${p1} (White) wins.`;
case 'checkmate_black': return `Checkmate! ${p2} (Black) wins.`;
case 'stalemate': return "Stalemate! It's a draw.";
case 'draw_agreement': return "Draw by agreement."; // Not implemented
case 'aborted': return "Game aborted.";
case 'active':
case 'waiting':
default:
return false; // Game is not over
}
}
// --- Core Chess Logic ---
function createLabels() {
const files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const ranks = ['8', '7', '6', '5', '4', '3', '2', '1'];
topFilesLabel.innerHTML = ''; bottomFilesLabel.innerHTML = ''; leftRanksLabel.innerHTML = ''; rightRanksLabel.innerHTML = '';
// Flip labels if board is flipped for black player in friend mode
const boardIsFlipped = (gameMode === 'friend' && playerColor === 'black');
const displayFiles = boardIsFlipped ? [...files].reverse() : files;
const displayRanks = boardIsFlipped ? [...ranks].reverse() : ranks;
displayFiles.forEach(file => { const tl = document.createElement('div'); tl.classList.add('label'); tl.textContent = file; topFilesLabel.appendChild(tl); const bl = document.createElement('div'); bl.classList.add('label'); bl.textContent = file; bottomFilesLabel.appendChild(bl); });
displayRanks.forEach(rank => { const ll = document.createElement('div'); ll.classList.add('label'); ll.textContent = rank; leftRanksLabel.appendChild(ll); const rl = document.createElement('div'); rl.classList.add('label'); rl.textContent = rank; rightRanksLabel.appendChild(rl); });
}
function prepareTurn() {
console.log(`prepareTurn START: CurrentPlayer=${currentPlayer}, PlayerColor=${playerColor}, GameOver=${gameOver}`);
selectedPiece = null;
validMoves = [];
updateCheckStatus(); // Check if current player is in check based on current board state
// Determine if it's this browser's player's turn based on updated state
isMyTurn = !gameOver && (gameMode === 'self' || (gameMode === 'friend' && currentPlayer === playerColor));
console.log(`prepareTurn: Is my turn now? ${isMyTurn}`);
// Find clickable pieces *only if* it's my turn and game not over
initialClickablePieces = (isMyTurn && !gameOver) ? findClickablePieces() : [];
console.log(`prepareTurn: Found ${initialClickablePieces.length} clickable pieces.`);
// Game end status is primarily determined by received state in friend mode ('gameOver' var)
// Only run local checkmate/stalemate logic for self-play mode to update the gameOver flag locally
if (!gameOver && gameMode === 'self') {
checkGameEndLocally(); // This updates the 'gameOver' variable for self-play
}
updateStatusDisplay(); // Update text based on current state (including gameOver)
renderBoard(); // Render based on current state
// Ensure listener is correctly attached/detached based on final turn status
chessboardElement.removeEventListener('click', handleSquareClick);
if (!gameOver && isMyTurn) {
chessboardElement.addEventListener('click', handleSquareClick);
console.log("prepareTurn: Added click listener.");
} else {
console.log("prepareTurn: Did NOT add click listener (game over or not my turn).");
}
console.log(`prepareTurn END: IsMyTurn=${isMyTurn}, GameOver=${gameOver}`);
}
function renderBoard() {
chessboardElement.innerHTML = ''; // Clear previous state
const boardIsFlipped = (gameMode === 'friend' && playerColor === 'black');
for (let r_disp = 0; r_disp < 8; r_disp++) { // Display row
for (let c_disp = 0; c_disp < 8; c_disp++) { // Display col
// Map display coordinates to logical board coordinates
const r = boardIsFlipped ? 7 - r_disp : r_disp;
const c = boardIsFlipped ? 7 - c_disp : c_disp;
const piece = board[r]?.[c]; // Use optional chaining for safety
if (typeof board[r] === 'undefined') {
console.error(`Error accessing board row ${r} (Display: ${r_disp})`); continue;
}
let element;
let isSelectable = false; // Can this piece be selected?
let isSelected = false; // Is this the currently selected piece?
let isValidTarget = false; // Is this a valid move target square?
let isCaptureTarget = false; // Is this a capture target?
// Determine interaction states ONLY if it's my turn and game isn't over
if (!gameOver && isMyTurn) {
if (selectedPiece) {
// State: A piece is selected
if (r === selectedPiece.row && c === selectedPiece.col) {
isSelectable = true; // Allow deselecting the selected piece
isSelected = true;
} else {
isValidTarget = validMoves.some(move => move.row === r && move.col === c);
if (isValidTarget) {
isSelectable = true; // Target squares are clickable
// Check for capture (opponent piece OR en passant target square)
isCaptureTarget = piece !== null ||
(selectedPiece.piece.type === 'pawn' && c !== selectedPiece.col && piece === null && enPassantTarget && r === enPassantTarget.row && c === enPassantTarget.col);
}
}
} else {
// State: No piece selected - check initial clickable pieces for *my* color
isSelectable = initialClickablePieces.some(p => p.row === r && p.col === c);
}
}
// Create the element (button if interactive, div otherwise)
element = document.createElement(isSelectable ? 'button' : 'div');
element.classList.add('square-base');
element.classList.add(isSelectable ? 'square-button' : 'square-div');
// Add standard classes (light/dark based on logical coords)
element.classList.add((r + c) % 2 === 0 ? 'light' : 'dark');
element.dataset.row = r; // Store logical row/col
element.dataset.col = c;
// Add chess notation (visually hidden text)
const notation = getNotation(r, c);
element.textContent = notation;
// Add piece content and color class using pseudo-element
if (piece) {
element.dataset.pieceSymbol = piece.unicode;
element.classList.add(piece.color);
element.classList.add('has-piece');
}
// Add interaction classes (only if it's a button)
if (isSelectable) {
if (isSelected) {
element.classList.add('selected');
} else if (isValidTarget) {
element.classList.add(isCaptureTarget ? 'capture-move' : 'valid-move');
}
}
// Append using display coordinates
chessboardElement.appendChild(element);
}
}
}
function handleSquareClick(event) {
const targetButton = event.target.closest('.square-button');
// Ignore if not a button, not my turn, or game is over
if (!targetButton || !isMyTurn || gameOver) {
// console.log("Click ignored: Not interactive", { isMyTurn, gameOver }); // Reduce noise
return;
}
const row = parseInt(targetButton.dataset.row);
const col = parseInt(targetButton.dataset.col);
if (isNaN(row) || isNaN(col)) {
console.error("Invalid row/col data on button:", targetButton);
return;
}
if (selectedPiece) {
// State: Piece is selected
if (row === selectedPiece.row && col === selectedPiece.col) { // Clicked selected piece -> Deselect
selectedPiece = null;
validMoves = [];
renderBoard(); // Re-render to show initial pieces selectable again
} else {
const isTarget = validMoves.some(move => move.row === row && move.col === col);
if (isTarget) { // Clicked a valid move target -> Make the move