-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchessbot.py
More file actions
824 lines (701 loc) · 32.2 KB
/
Copy pathchessbot.py
File metadata and controls
824 lines (701 loc) · 32.2 KB
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
# -*- coding: utf-8 -*-
"""chessbot.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1lUgHIQN3kwtdorB3trls92B8pu1dwH5a
"""
import numpy as np
import re
# from enum import IntEnum
#NEW CHALLENGE: implement all objects as numpy arrays.
#include binary masks to represent board state and valid moveset.(vectorise masks with position)
#include caching of boardstates
#try encoding values in terms of:
# // value of all currently possible board position:
# // opponents pieces captured or in captur-able positions(next move: * decay) upon moving there
# // danger value of own pieces in captur-able position(s) upon moving there
# only for heuristics to search faster.
#then build a simple version with a numpy array of possibilities for each move in moveset, and pick from these possibilities
#start with equal but add based on feedback (board state feedback will add to all previous moves but diminishing)
#easy lvl-1: no board input to function. outputs: (row(8), col(8), piece(5), dir(3-8), size(1-8)) rlly just blind and softmax remaining options.
# distinct probability to each of 5 outputs, will just mask invalid outputs (ie. not calculate them)
# dont bother punishing invalid moves, just mask.
# lvl 1.5-1: each combination of outputs has a distinct probability. Use idx_chosen(probabilistically) to find output match.
#lvl 1.5-2: include separate probability for early, mid and late game(mix by ratio, depend on movecount and remaining piece count. will be overwrit by lvl 3.)
#technically at the end of training I can prune anything with probability < 0.01. pick at random if all remaining options had been pruned.
# actually I only softmax and pick at random each game.
# if the remaining probabilities = 0 then it will have to pick at random and hope it wins.
# so if a move is never legal its weight just never updates.
# it won't be pruned, unless I set a specific counter of whether a probability has been updated.
#this counter should also factor into whether a weight is kept, and will be deleted before saving.
#lvl 2: half-inform probabilities by allowing minimax of board_state in 5 moves. (pls make this optimised first)
# ie: use most probable move from a trained lvl 1 algorithm to inform the min/max heuristic values after 5 moves.
#lvl 3: perceptron from encoded boardstate to board. Consider saving midstates to update instead of replace calculations.
#use ints for math precision and speed when in numpy.
#please cache the board to let it resample previous states, playing from midgame.
#best to guide with a minimax-ish player to avoid dead loops
# perhaps include best boardstate from minimax-depth5 for input or feedback. proceed to minimax the top 5 outputs.
#lvl 4: pytorch. entirely overwrites everything else, but at least its good to check if the logic is sound first.
#lvl 5: pytorch-guided alpha-beta-pruned minimax. uses decision model and eval model: only deviates by last layer.
#lvl 6: build all of the above, including cache and evals by all boards, then eval games based on eval by models (weighted by historical accuracy in predicting wins)
#lvl 2 cannot learn :( best as a wrapper for other models.
"""# SETUP"""
BOARD_SIZE = 8
PLAYER_ID = -1 #pawns will move 'up'
#BLACK
COMP_ID = 1 #pawns will move 'down'
#WHITE
PAWN = 1
BISHOP = 5
KNIGHT = 6
ROOK = 8
QUEEN = 10
KING = 100
BLANK = None
BACK_RANK = [ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK]
move_encodings = { #only the general possibilities for direction(Should be relative to player.)
PAWN:np.array([(0,1),(1,1),(-1,1)]),
BISHOP:np.array([(1,1),(1,-1),(-1,1),(-1,-1)]),
ROOK: np.array([(1, 0), (-1, 0), (0, 1), (0, -1)]),
KNIGHT: np.array([(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]),
QUEEN:np.array([(1,1),(1,-1),(-1,1),(-1,-1), (1, 0), (-1, 0), (0, 1), (0, -1)]),
KING: np.array([(1,1),(1,-1),(-1,1),(-1,-1), (1, 0), (-1, 0), (0, 1), (0, -1)])
}
valid_reach_pieces = { #only the general possibilities for direction(Should be relative to player.)
PAWN:2, # PAWN, move_size 2 only valid if pos is initial pos.
BISHOP:BOARD_SIZE,
ROOK: BOARD_SIZE,
KNIGHT: 1,
QUEEN:BOARD_SIZE,
KING: 2
}
"""Structure of attributes in all classes:
class pieces:
def __init__(self, board, name, player, value, position,en_passant,can_castle):
self.board = board
self.name = name #str
self.player = player #CONST{1,-1}
self.value = value #CONST
self.start_pos = position #[x,y]
self.position = position #[x,y]
self.dead = False
self.en_passant = en_passant
self.can_castle = can_castle
self.castled = False
class board_class:
def __init__(self):
self.chess_board = np.full((8,8), BLANK, dtype=object)
self.en_passant = [0,0] #column of last en_passant, counter
self.can_castle = {PLAYER_ID:[True,True],COMP_ID:[True,True]} #left, right.
#chess_board is NOT global.
# self.boardpieces = [] #pieces removed upon loss
self.player_pieces = [] #pieces NOT removed upon loss.
self.comp_pieces = []
self.allpieces = {
COMP_ID: self.comp_pieces,
PLAYER_ID: self.player_pieces
}
self.dead_piece = None
computerize:
def __init__(self, board,player):
self.board = board
self.player = player
self.current_turn = current_turn
self.badmoves = 0
class player_inputs:
def __init__(self,board,player,current_player):
self.board = board
self.player = player
self.current_player = current_player
# utils
"""
class pieces:
def __init__(self, board, name, player, value, position,en_passant,can_castle):
self.board = board
self.name = name #str
self.player = player #CONST{1,-1}
self.value = value #CONST
self.start_pos = position #[x,y]
self.position = position #[x,y]
self.dead = False
self.en_passant = en_passant
self.can_castle = can_castle
self.castled = False
#CONSIDER ALLOW PARALLEL PROCESSING with array of possible moves
#I do want to make it human playable...at most ill make a separate parallel ver.
def is_valid_for_piece(self, move_dir, move_size, const = False):
#THIS IS NOT A CONST FUNCTION BY DEFAULT DUE TO EN_PASSANT.
#pass True in 3rd param to use for testing.
if 0 <= move_dir < len(move_encodings[self.value]):
if 0 < move_size <= valid_reach_pieces[self.value]:
if self.value == KING:
if move_size > 1:
if (piece.can_castle[0] and move_dir == 7) or (piece.can_castle[1] and move_dir == 6):
# for i in range(1,BOARD_SIZE//2+1)
i = 1
piece = KING
while piece != ROOK and i < BOARD_SIZE//2+1:
move = move_encodings[self.value][move_dir] * i
move *= self.player
pos = np.array(self.position) + move
if 0 <= pos[0] < BOARD_SIZE and 0 <= pos[1] < BOARD_SIZE: #avoid out of bounds err.
piece = self.board[ tuple(pos)]
if piece is not BLANK and piece != ROOK:
return False
else:
break
i += 1
if pos[1] == 0 or pos[1] == BOARD_SIZE - 1:
self.castled = True
return True
else:
return False
if self.value == PAWN:
if move_size == 2:
if self.start_pos == self.position and move_dir == 0:
move = move_encodings[self.value][move_dir]
move *= self.player # use move[0] to affect only rows
pos1 = np.array(self.position) + move
pos2 = np.array(self.position) + move * 2
if 0 <= pos1[0] < BOARD_SIZE and 0 <= pos1[1] < BOARD_SIZE:
if 0 <= pos2[0] < BOARD_SIZE and 0 <= pos2[1] < BOARD_SIZE:
if self.board[ tuple(pos1)] == BLANK and self.board[ tuple(pos2)] == BLANK:
if not const:
self.en_passant[0] = self.position[1]
self.en_passant[1] = 1
return True
return False #ONLY if move_size == 2 AND not returned True
move = move_encodings[self.value][move_dir] * move_size
move *= self.player
pos = np.array(self.position) + move
if 0 <= pos[0] < BOARD_SIZE and 0 <= pos[1] < BOARD_SIZE: #avoid out of bounds err.
if move_dir == 0: #forward.
if self.board[ tuple(pos)] is not BLANK:
return False
else: #eating
if self.board[ tuple(pos)] == BLANK or self.board[ tuple(pos)] == self.player:
if self.en_passant[0] == pos[1] and self.en_passant[1] == 0:
pos[0] -= self.player #
if self.board[ tuple(pos)] is not BLANK:
if not const:
self.en_passant[0] = -1
return True
return False
else:
return False
#END OF PAWN BLOCK
return True
return False
def check_blocks(self,prev_pos, new_pos,move_dir,move_size):
#CONST FUNCTION
for i in range(1,move_size):
move = move_encodings[self.value][move_dir] * move_size
move *= self.player
pos = np.array(self.position) + move
if self.board[ tuple(pos)] is not BLANK: #if BLANK, has no player attribute.
#blocked by anything
return False
move = move_encodings[self.value][move_dir] * move_size
move *= self.player
pos = np.array(self.position) + move
if self.board[ tuple(pos)] is not BLANK and self.board[ tuple(pos)].player == self.player: #make use of lazy processing
#blocked by ourselves
return False
return True
def upgrade_pawn(self, new_value = QUEEN):#auto-check, then allow user_input value for this.
if self.value == PAWN and self.position[0] == BOARD_SIZE - 1 or self.position[0] == 0:
self.value = new_value
return True
return False
def update_pos(self,move_dir,move_size):
if self.is_valid_for_piece(move_dir,move_size):
move = move_encodings[self.value][move_dir] * move_size
move *= self.player
temp_pos = np.array(self.position) + move
if 0 <= temp_pos[0] < BOARD_SIZE and 0 <= temp_pos[1] < BOARD_SIZE:
if self.check_blocks(self.position,temp_pos,move_dir,move_size) :
self.position = list(temp_pos)
return self.position
return None #(if invalid)
def check_pos(self,move_dir,move_size):
if self.is_valid_for_piece(move_dir,move_size,const = True):
move = move_encodings[self.value][move_dir] * move_size
move *= self.player
temp_pos = np.array(self.position) + move
if 0 <= temp_pos[0] < BOARD_SIZE and 0 <= temp_pos[1] < BOARD_SIZE:
if self.check_blocks(self.position,temp_pos,move_dir,move_size) :
return list(temp_pos) #new position of piece on board.
return None #(if invalid)
def undo(self,move_dir,move_size):#assume valid. only affects internal state.
move = move_encodings[self.value][move_dir] * move_size
move *= self.player
temp_pos = np.array(self.position) - move
self.position = list(temp_pos)
def print_pos(self): #mostly debug?
print("piece: ",self.name,"at",chr(ord('a') + self.position[1]),self.position[0])
class board_class:
def __init__(self):
self.chess_board = np.full((8,8), BLANK, dtype=object)
self.en_passant = [0,0] #column of last en_passant, counter
self.can_castle = {PLAYER_ID:[True,True],COMP_ID:[True,True]} #left, right.
#chess_board is NOT global.
# self.boardpieces = [] #pieces removed upon loss
self.player_pieces = [] #pieces NOT removed upon loss.
self.comp_pieces = []
self.allpieces = {
COMP_ID: self.comp_pieces,
PLAYER_ID: self.player_pieces
}
self.dead_piece = None
for i in range(8):
#all pawns
p = pieces(self.chess_board, f"p_pawn_{i}", PLAYER_ID, PAWN, [6, i],self.en_passant,self.can_castle[PLAYER_ID])
# self.boardpieces.append(p)
self.player_pieces.append(p)
self.chess_board[6, i] = p
for i in range(8): #specifically to keep boardpieces looking neat.
# Player Major Pieces (Row 7)
p_user = pieces(self.chess_board, f"p_{BACK_RANK[i]}_{i}", PLAYER_ID, BACK_RANK[i], [7, i],self.en_passant,self.can_castle[PLAYER_ID])
# self.boardpieces.append(p_user)
self.player_pieces.append(p_user)
self.chess_board[7, i] = p_user
#try using: if isinstance(self.chess_board[new_pos], pieces)
for i in range(8):
p = pieces(self.chess_board, f"c_pawn_{i}", COMP_ID, PAWN, [1, i],self.en_passant,self.can_castle[COMP_ID])
# self.boardpieces.append(p)
self.comp_pieces.append(p)
self.chess_board[1, i] = p
for i in range(8):
# Computer Major Pieces (Row 0)
p_comp = pieces(self.chess_board, f"c_{BACK_RANK[i]}_{i}", COMP_ID, BACK_RANK[i], [0, i],self.en_passant,self.can_castle[COMP_ID])
# self.boardpieces.append(p_comp)
self.comp_pieces.append(p_comp)
self.chess_board[0, i] = p_comp
def check_movespace(self,player,check_king = False,any_valid_moves = False):
# just loop through board.boardpieces and ask each piece for its moves
# skipping the pieces where dead == True.
test = False
dir = 0
size = 0
for piece in self.allpieces[player]:
if piece.dead:
continue
for dir in range(len(move_encodings[piece.value])):
for size in range(1,valid_reach_pieces[piece.value]+1):
new_pos = piece.check_pos(dir,size)
if new_pos is not None:
if check_king:
test = (self.chess_board[tuple(new_pos)] is not BLANK and self.chess_board[tuple(new_pos)].value == KING and self.chess_board[tuple(new_pos)].player != player)
if any_valid_moves:
test = self.king_unsafe(player)
#since check_pos is True. the only illegal possibility is king is unsafe.
if test:
return test
else:
break # stop checking this direction
# most likely the dir is bad, already hit wall or item.
def king_unsafe(self,player):
return self.check_movespace(player * -1 , check_king = True)
#castling done
def player_move(self,player,position,move_dir,move_size): #ENSURE PLAYERS CAN ONLY MOVE THEIR OWN PIECE...
position = tuple(position)
if player == self.chess_board[position].player:
return self.update_board(position,move_dir,move_size) #returns piece or False(failed)
return False
def update_board(self,prev_pos,move_dir,move_size):
temp_no_castle = [False,False]
self.dead_piece = None
prev_pos = tuple(prev_pos)
# board_copy = self.chess_board.copy()
piece = self.chess_board[prev_pos]
if piece.value == KING:
if piece.can_castle:
if self.king_unsafe(piece.player):
temp_no_castle = piece.can_castle
piece.can_castle = [False,False]
new_pos = piece.update_pos(move_dir,move_size)
if new_pos is not None:
new_pos = tuple(new_pos)
self.chess_board[prev_pos] = BLANK
if self.chess_board[new_pos] is not BLANK:
#Marking previous piece as dead
self.dead_piece = self.chess_board[new_pos]
self.chess_board[new_pos].dead = True
# self.boardpieces.remove(self.chess_board[new_pos])
self.chess_board[new_pos] = piece
if self.en_passant[0] == -1:
self.en_passant[0] = 0
temp_pos = list(new_pos)
temp_pos[0] -= piece.player
self.dead_piece = self.chess_board[tuple(temp_pos)]
self.chess_board[temp_pos].dead = True
# self.boardpieces.remove(self.chess_board[temp_pos])
self.chess_board[temp_pos] = BLANK
#temp_pos auto-deletes every function call.
if self.king_unsafe(piece.player):
piece.undo(move_dir,move_size)
self.chess_board[prev_pos] = piece
# self.chess_board = board_copy
if temp_pos is not None:#temp_pos only occurs if an en_passant was captured...
self.chess_board[temp_pos] = self.dead_piece
self.chess_board[temp_pos].dead = False
elif self.dead_piece is not None:
self.chess_board[new_pos] = self.dead_piece
self.chess_board[new_pos].dead = False
self.dead_piece = None
if self.en_passant[1] == 1:
self.en_passant[1] = -1 #since the en_passant was undone.
return False
if piece.castled: # MOVE ROOK.
# because honestly castle cannot be done under check and rook placement will not save from check
if move_dir == 6:
rook = self.chess_board[new_pos[0],BOARD_SIZE - 1]
new_pos = list(new_pos)
new_pos[1] -=1
new_pos = tuple(new_pos)
size = BOARD_SIZE - 1 - new_pos[1]
rook.undo(2,size)#cus im lazy.
# original move_dirs: 2 moves right 3 moves left
self.chess_board[new_pos[0],BOARD_SIZE - 1] = BLANK
self.chess_board[new_pos] = rook
if move_dir == 7:
rook = self.chess_board[new_pos[0],0]
new_pos = list(new_pos)
new_pos[1] +=1
new_pos = tuple(new_pos)
size = new_pos[1] # - 0
rook.undo(3,size)
self.chess_board[new_pos[0],0] = BLANK
self.chess_board[new_pos] = rook
piece.castled == False
if temp_no_castle[0]:
piece.can_castle[0] = True
if temp_no_castle[1]:
piece.can_castle[1] = True
if piece.value == KING or (piece.value == ROOK and piece.position[1] ==0):
piece.can_castle[0] = False
if piece.value == KING or (piece.value == ROOK and piece.position[1] ==BOARD_SIZE - 1):
piece.can_castle[1] = False
self.en_passant[1] -= 1#update counter
return piece
return False
def check_mate_check(self, player):#TODO.
if self.king_unsafe(player):
if self.check_movespace(player , any_valid_moves = True):
return True
return False
def calculate_board_score(self,player):
# Sum the 'value' of all pieces that aren't dead
if self.check_mate_check(player):
return -1000
if self.check_mate_check(player * -1):
return 1000
player_score = sum(p.value for p in self.player_pieces if not p.dead)
comp_score = sum(p.value for p in self.comp_pieces if not p.dead)
return (comp_score - player_score) #+ve value: comp > player.
def print_board(self): # AI ver. ok.
width = 10
# Create the letter labels for the top and bottom
col_labels = " " + "".join(chr(ord('a') + i).center(width + 1) for i in range(BOARD_SIZE))
divider = " " + "-" * (width * BOARD_SIZE + BOARD_SIZE + 1)
print(col_labels)
for i, row in enumerate(self.chess_board):
print(divider)
row_cells = []
for cell in row:
name = str(cell.name) if cell is not BLANK else " "
row_cells.append(name.center(width))
# Chess ranks usually go 8 down to 1 from top to bottom
rank_num = BOARD_SIZE - i
print(f" {rank_num} |" + "|".join(row_cells) + "|")
print(divider)
print(col_labels)
"""# Interactive"""
class computerize:
# create 12 different 8x8 grids (channels).
# Channels 1-6 are for your pieces (Pawn, Knight, Bishop, Rook, Queen, King).
# Channels 7-12 are for opponent pieces.In each grid, put a 1 where the piece is and a 0 everywhere else.
# OR just use the numerical representation board its fine
# Whose turn it is (1 or -1).
# Castling rights (True/False flags).
# En Passant square (The coordinate you've been tracking).
#TODO make use of this to let RL play...
pass
def __init__(self, board,player,current_turn):
self.board = board
self.encoded_board = None
self.player = player
self.current_turn = current_turn
self.badmoves = 0
self.board_score = 0
def set_rl_state(self): #RETURNS full boardview with metadata.
#one_hot version:
#TODO: ONLY UPDATE CHANGES.
self.badmoves = 0 #since this function calls everytime the board is read...
encoded_board = np.zeros((17, BOARD_SIZE, BOARD_SIZE), dtype=np.float32)
for p in self.board.player_pieces:
if p.dead: continue
piece = p.value
if piece != PAWN:
piece = BACK_RANK.index(piece)
# piece = piece + 6 if p.player == COMP_ID
coor = (piece,p.position[0],p.position[1])
encoded_board[coor] = 1.0 #p.value * p.player
for p in self.board.comp_pieces:
if p.dead: continue
piece = p.value
if piece != PAWN:
piece = BACK_RANK.index(piece)
piece = piece + 6 #if p.player == COMP_ID
coor = (piece,p.position[0],p.position[1])
encoded_board[coor] = 1.0 #p.value * p.player
if self.current_turn == PLAYER_ID:
encoded_board[12, :, :] = 1.0
# Map dictionary booleans to full 8x8 planes
if self.board.can_castle[PLAYER_ID*self.player][0]: encoded_board[13, :, :] = 1.0 # self Queenside
if self.board.can_castle[PLAYER_ID*self.player][1]: encoded_board[14, :, :] = 1.0 # self Kingside
if self.board.can_castle[COMP_ID*self.player][0]: encoded_board[15, :, :] = 1.0 # other Queenside
if self.board.can_castle[COMP_ID*self.player][1]: encoded_board[16, :, :] = 1.0 # other Kingside
if self.board.en_passant[1] >= 0: # If counter is active
col = self.board.en_passant[0]
row = 2 if self.current_turn == PLAYER_ID else 5
encoded_board[17, row, col] = 1.0
if self.player == COMP_ID:
encoded_board = np.flip(encoded_board, axis=(1,2))#flip rows and cols (rotate 180)
# DELETED: Returns an 8x8 array where White is (+) and Black is (-)
# encoded_board = np.array([[p.value * p.player if p is not BLANK else 0 for p in row] for row in self.board.chess_board])
self.encoded_board = encoded_board
return encoded_board
def update_board_state(self,prev_pos, p):
piece = p.value
if piece != PAWN:
piece = BACK_RANK.index(piece)
piece = piece + 6 if p.player == COMP_ID
coor_new = (piece,p.position[0],p.position[1])
self.encoded_board[coor_new] = 1.0 #p.value * p.player
coor_old = (piece,prev_pos[0],prev_pos[1])
self.encoded_board[coor_old] = 0.0 #p.value * p.player
piece = self.dead_piece.value
if piece != PAWN:
piece = BACK_RANK.index(piece)
piece = piece + 6 if self.dead_piece.player == COMP_ID
coor_dead = (piece,p.position[0],p.position[1])
self.encoded_board[coor_dead] = 0.0 #p.value * p.player
self.encoded_board[12:, :, :] = 0.0
if self.current_turn == PLAYER_ID:
encoded_board[12, :, :] = 1.0
if self.board.can_castle[PLAYER_ID*self.player][0]: self.encoded_board[13, :, :] = 1.0 # self Queenside
if self.board.can_castle[PLAYER_ID*self.player][1]: self.encoded_board[14, :, :] = 1.0 # self Kingside
if self.board.can_castle[COMP_ID*self.player][0]: self.encoded_board[15, :, :] = 1.0 # other Queenside
if self.board.can_castle[COMP_ID*self.player][1]: self.encoded_board[16, :, :] = 1.0 # other Kingside
if self.board.en_passant[1] >= 0: # If counter is active
col = self.board.en_passant[0]
row = 2 if self.current_turn == PLAYER_ID else 5
self.encoded_board[17, row, col] = 1.0
def get_rl_score(self): #positive is good.
#calculate_board_score: +ve value: comp > player.
if self.board_score == 0:
self.board_score = self.board.calculate_board_score(self.player) * self.player
return self.board_score - self.badmoves
def comp_play(self,tensor, pawn = False): #ONLY CALL UPON MOVE
#RECEIVES network outputs
#network is constrained to choose from living board pieces.
# ignore. piece = self.board.allpieces[self.player][piece_idx]
# If allpieces[10] is dead, the network’s probability for that index must be set to 0 before it chooses.
# mask = [0 if p.dead else 1 for p in self.allpieces[self.player]]
pass
# tensor_size = (BOARD_SIZE,BOARD_SIZE,BOARD_SIZE,BOARD_SIZE)
# tensor: position(0-7)*(0-7), move_dir(0-7),move_size(0-7)
# model returns 2 objects: tensor, preferred pawn promotion(0-3) for boardstate
# consider to mask pawn output nodes during the rest of the game.
# position, move_dir,move_size being the coor. of MAX_probability value within tensor.
status = self.board.player_move(self.player, position, move_dir,move_size) #TODO
#position is used as player_move input because human players input position_like.
# preferred_piece = BACK_RANK[piece_value] if piece_value < 5 else PAWN
preferred_piece = QUEEN
if status == False:
self.badmoves += 1
else:
status.upgrade_pawn(preferred_piece)
#receives input in the form: move PIECE from (A4) to (E4)
#return values that can be fed into pieces etc.
class player_inputs:
def __init__(self,board,player,current_player):
self.board = board
self.player = player
self.current_player = current_player
def to_indices(self,file_char, rank_char):
col = ord(file_char.lower()) - ord('a')
row = BOARD_SIZE - int(rank_char)
return np.array([row, col])
def parse_human_move(self, piece_value, pos1, pos2):
# Regex to find two coordinates like (A4) or (E4)
# [a-h] matches the file, [1-8] matches the rank
try:
piece_value = abs(int(piece_value))
except ValueError:
print("please input an integer to represent the piece")
return None
coord1 = re.findall(r'([a-hA-H])([1-8])', pos1)
coord2 = re.findall(r'([a-hA-H])([1-8])', pos2)
if coord1 is None or len(coord1) < 1:
print("Could not parse start coordinates. Use format: <Letter><number>")
print("received: ",coord1)
return None
if coord2 is None or len(coord2) < 1:
print("Could not parse end coordinates. Use format: <Letter><number>")
print("received: ",coord2)
return None
if coord1 == coord2:
print("please do not move back to original position.")
coord1 = coord1[0]
coord2 = coord2[0]
# Helper to convert 'a4' -> [row 4, col 0]
start_pos = self.to_indices(coord1[0], coord1[1])
end_pos = self.to_indices(coord2[0], coord2[1])
# Calculate vector for direction and size
board_piece = self.board.chess_board[tuple(start_pos)]
player_piece = BACK_RANK[piece_value] if piece_value < 5 else PAWN
if board_piece.value != player_piece:
print("intended piece not at given coordinates. Please input again.")
print("received: ",piece_value)
return None
if board_piece.player != self.player:
print("intended piece not your piece. Please input again.")
return None
vector = end_pos - start_pos
# scale = max(vector[0]//vector[1],vector[1]//vector[0]) #FAILED.
scale = 0
for scale in range(max(abs(vector)),0,-1):
if vector[0]%scale ==0 and vector[1]%scale ==0:
break
if scale == 0: return None
# Normalize vector to find move_dir index in your move_encodings
# We divide by move_size to get a unit vector like [-1, 0] or [1, 1]
dir = (vector // scale).tolist()
adjusted_dir = [dir[0] // self.player, dir[1]]
try:
indices = np.where(move_encodings[board_piece.value] == adjusted_dir)[0]
return start_pos, indices[0], scale
except ValueError:
return None
def pawn_check(self, piece):
while True:
if piece.value == PAWN and piece.position[0] == BOARD_SIZE - 1 or piece.position[0] == 0:
#INPUT FUNCTION. TODO if GUI.
print("please input a numerical value to represent the piece to upgrade:")
print("0: ROOK, 1: KNIGHT, 2: BISHOP, 3: QUEEN")
piece_value = input()
try:
piece_value = abs(int(piece_value))
player_piece = BACK_RANK[piece_value]
piece.upgrade_pawn(player_piece)
except ValueError:
print("please input an integer(0-3) to represent the piece to upgrade:")
return None
def play(self):
while True:
print("please input a numerical value to represent the piece:")
print("0: ROOK, 1: KNIGHT, 2: BISHOP, 3: QUEEN, 4: KING, 5: PAWN") #actually recognises anything >4 as PAWN.
piece_value = input()
pos1 = input("Please input the starting position in the form (A4)")
pos2 = input("Please input the target position in the form (A4)")
ret_val = self.parse_human_move(piece_value, pos1, pos2)
if ret_val is not None:
position,move_dir,move_size = ret_val
move = self.board.player_move(self.player,position,move_dir,move_size)
if move:
self.pawn_check(move)
break
# if name == main...
my_board = board_class()
current_player = PLAYER_ID
# comp_1 = computerize(my_board,COMP_ID,current_player)
player_1 = player_inputs(my_board,PLAYER_ID,current_player) #-1
player_2 = player_inputs(my_board,COMP_ID,current_player) # 1.
while True:
my_board.print_board() #TODO: add GUI with drag (converts to player input)
if current_player == COMP_ID:
player = player_2
colour = 'White'
else:
player = player_1
colour = 'Black'
print(f"\n{colour}'s turn.")
player.play()
if (my_board.calculate_board_score(current_player)< -500):
print("Player 1 (BLACK) has won")
break
if (my_board.calculate_board_score(current_player)> 500):
print("Player 1 (BLACK) has lost")
break
if current_player == COMP_ID:
current_player = PLAYER_ID
else:
current_player = COMP_ID
"""# RL BOT
Consider implementing stalemate rules etc
Especially cap total move limit per game
Try adding a value head for confodence
Zero out illegal start positions, move dir, and move sizes before softmaxing in the network.
To let the model get better at learning how good its moves are
Mask out pawn promotion unless pawn exists in 2nd last row. Also do not include that node in softmax. its a separate category.
Otherwise 4096 possibilities is rlly too much
Add random shifts to force exploration: by 'choosing' between values based on the probability output, not taking the max only
Maybe after every game, update probabilities by learning rate * score. use cross-entropy loss.
Consider using random initialization. Boards at first
Store board states. Design training on previously saved states.
Aim for at least 10000 moves per second
Eg. Boundary checking with np.nonzero()
Try to keep the directions as consistent as possible so the same outputs have the same meaning regardless of piece
Just check that the castle still works.... maybe forgot to check king move dir??
Also, maybe add a const value for the actual idx of the required directions...
More readable, too.
Can consider 8row 8col 8dir 8size for performance
For one-hot, stick to 1 for all values
Inputs stick to between 0 to 1
Consider feeding castle and enpass by new inputs at the end, deep layers (not conv.)
Use 4 separate heads + 1
Heads is fully connected layer?
"""
#RL bot
#Every time it makes a move, it records: (Current State, Action Taken, Reward Received, Next State).
import torch
import torch.nn as nn
import torch.nn.functional as F
# AI gen.
class ChessNet(nn.Module):
def __init__(self):
super(ChessNet, self).__init__()
# 1. THE BACKBONE: 17 input planes -> CNN
# We use padding=1 to keep the board size at 8x8 throughout
self.conv1 = nn.Conv2d(17, 64, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(64)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
self.bn2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.bn3 = nn.BatchNorm2d(128)
# 2. THE HEADS: Branching off the CNN features
# Flattening 128 channels * 8 * 8 board = 8192 features
self.fc_common = nn.Linear(128 * 8 * 8, 512)
self.head_row = nn.Linear(512, 8)
self.head_col = nn.Linear(512, 8)
self.head_dir = nn.Linear(512, 8)
self.head_size = nn.Linear(512, 8)
self.head_pawn = nn.Linear(512, 4) # 4 pieces: Q, N, R, B
def forward(self, x):
# Body logic
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = x.view(-1, 128 * 8 * 8) # Flatten
x = F.relu(self.fc_common(x))
# Output branches
row = self.head_row(x)
col = self.head_col(x)
direction = self.head_dir(x)
size = self.head_size(x)
pawn = self.head_pawn(x)
return row, col, direction, size, pawn
# Initialize model
model = ChessNet()