forked from EphraimJZimmerman/chess_hackathon_23
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
91 lines (70 loc) · 2.84 KB
/
bot.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
"""
The Brandeis Quant Club ML/AI Competition (November 2023)
Author: @Ephraim Zimmerman
Email: [email protected]
Website: brandeisquantclub.com; quants.devpost.com
Description:
For any technical issues or questions please feel free to reach out to
the "on-call" hackathon support member via email at [email protected]
Website/GitHub Repository:
You can find the latest updates, documentation, and additional resources for this project on the
official website or GitHub repository: https://github.com/EphraimJZimmerman/chess_hackathon_23
License:
This code is open-source and released under the MIT License. See the LICENSE file for details.
"""
import random
import chess
import time
import numpy as np
from collections.abc import Iterator
from contextlib import contextmanager
from j_mct import MCTS, ChessGame
@contextmanager
def game_manager():
"""Creates context for game."""
print("===== GAME STARTED =====")
ping: float = time.perf_counter()
try:
# DO NOT EDIT. This will be replaced w/ judging context manager.
yield
finally:
pong: float = time.perf_counter()
total = pong - ping
print(f"Total game time = {total:.3f} seconds")
print("===== GAME ENDED =====")
# Add promotion stuff
if __name__ == "__main__":
with game_manager():
"""
Feel free to make any adjustments as you see fit. The desired outcome
is to generate the next best move, regardless of whether the bot
is controlling the white or black pieces. The code snippet below
serves as a useful testing framework from which you can begin
developing your strategy.
"""
# Initialize the game and MCTS parameters
chess_game = ChessGame()
args = {
'C': 1.41, # Exploration parameter
'num_searches': 1000 # Number of searches (iterations) for MCTS
}
mcts = MCTS(chess_game, args)
side = input("Enter 1 for White or 0 for Black")
side = chess.BLACK if side == 0 else chess.WHITE
# Main game loop
while not chess_game.board.is_game_over():
print('\n')
print(chess_game.board)
if chess_game.board.turn == side:
# MCTS player (White)
neutral_state = chess_game.change_perspective(chess_game.board, side)
mcts_probs = mcts.search(neutral_state, side)
action = chess_game.get_valid_moves(neutral_state)[np.argmax(mcts_probs)]
else:
# Random player (Black)
valid_moves = list(chess_game.board.legal_moves)
action = random.choice(valid_moves)
chess_game.board.push(action)
# Print the final board and the game result
print(chess_game.board)
print("Game result:", chess_game.board.result())