-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
96 lines (76 loc) · 2.49 KB
/
game.py
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
from move_selection import Minimax
import chess
import chess.pgn
import serializer
import logo
import numpy as np
import tensorflow as tf
import os
import io
import sys
"""
TODO:
Implement backend in Torch/Django + React frontend using a chessboard library
- Run game as a webserver
"""
def display_board(board, side):
unicode = None
if side:
unicode = board.unicode(borders=True)
else:
unicode = board.transform(chess.flip_vertical).unicode(borders=True)
print(unicode+'\n')
def play(location, option):
model: tf.keras.Model = tf.keras.models.load_model(location)
minimax = Minimax(model)
logo.show()
print('\n\n')
side = None
while side not in ['W', 'B']:
side = input('Play as:\nWhite (W) | Black (B) | Random (R) > ')
if side == 'R':
side = 'W' if np.random.uniform() < 0.5 else 'B'
side = side == 'W'
szr = serializer.Serializer(None)
if option == 'P':
pgn = chess.pgn.read_game(io.StringIO(input('Paste PGN:\n> ')))
for move in pgn.mainline_moves():
szr.board.push(move)
while not szr.board.is_game_over():
logo.show()
print('\n\n')
display_board(szr.board, side)
score = model.predict(np.expand_dims(szr.serialize(), 0))
print(f'ch0ss evaluation: {score}')
if szr.board.turn == side:
uci = None
while not szr.board.is_legal(uci):
if uci is not None:
print('Illegal move')
try:
uci = chess.Move.from_uci(input('Type your move:\n > '))
except ValueError:
print('Invalid move')
uci = None
if szr.board.is_legal(uci):
szr.board.push(uci)
else:
print('Illegal move.')
else:
print('ch0ss is thinking...')
move = minimax.search(szr.board, 3, side)
szr.board.push(move[1])
# value = model.predict(np.expand_dims(bitboard, 0))
if __name__ == '__main__':
logo.show()
print('\n\n')
if len(sys.argv) == 1 or not os.path.isdir(sys.argv[1]):
print('Model file location not found. Pass as an argument:')
print('\t> python game.py ./models/model\n')
else:
while True:
opt = input(
'Play ch0ss:\nNew game (N) | From PGN (P) | Exit (X) > ')
if opt == 'X':
sys.exit()
play(sys.argv[1], opt)