Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/AndreaTerenz/PyTablut. Tablut game client in Python. Made for challenge project for FAIKR course mo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248import sysfrom argparse import ArgumentParserfrom time import time
from icecream import ic
from Tablut import Tablutfrom connect import get_player_port, Connectionfrom gui import GUI
CLIENT_NAME = "topG"
# Exit error codesFAILED_CONN_ERR = 1FAILED_SYNC_ERR = 2BROKEN_PIPE_ERR = 3CONN_RESET_ERR = 4STATE_UPDATE_ERR = 5CONN_TIMEOUT_ERR = 6
errors = { FAILED_CONN_ERR: "Connection failed (Is the server running?)", FAILED_SYNC_ERR: "Sync not received", BROKEN_PIPE_ERR: "Broken connection", CONN_RESET_ERR: "Connection reset by peer", STATE_UPDATE_ERR: "Failed to receive update", CONN_TIMEOUT_ERR: "Connection timed out",}
def parse_arguments(): parser = ArgumentParser()
parser.add_argument("role", help="Player role (either 'BLACK' or 'WHITE')", choices=["BLACK", "WHITE"]) parser.add_argument("-p", "--port", help="Server connection port (defaults to 5800 for WHITE and 5801 for BLACK)", type=int) parser.add_argument("-i", "--ip", help="Server IP address (defaults to localhost)", default="localhost") parser.add_argument("-l", "--local", help="Do not connect to server and run player against itself locally", action="store_true") parser.add_argument("-t", "--max-turns", help="Maximum number of turns for local game (implies --local)", default=-1, type=int) parser.add_argument("-d", "--depth", help="Minmax tree maximum depth (default is 3, value <= 0 to ignore depth cutoff)", default=3, type=int)
args = parser.parse_args()
if args.local and args.max_turns <= 0: args.max_turns = 200
skip_conn = bool(args.local or (args.max_turns > 0))
port = args.port if not port: port = get_player_port(args.role)
return args.role, args.ip, port, skip_conn, args.depth, args.max_turns
def run_locally(role, opponent, max_turns, minmax_depth): print(f"Max number of turns per player: {max_turns}")
ui = GUI(title=CLIENT_NAME) tablut = Tablut(role) tablut.board.print_grid() ui.draw(tablut.board)
print("#####################################")
i = 0 for i in range(max_turns * 2): # Alternate black and white turn = role if (i % 2) == 0 else opponent
print(f"----------------{turn} (turn {i})")
print("Initial board:") tablut.board.print_grid()
done = False escapes = tablut.board.available_escapes() before = after = time()
if turn == "WHITE" and len(escapes) > 0: print(f"Escape cell available in {escapes[0]}") move = tablut.board.king, escapes[0] done = True else: print("Searching move...") before = time() tablut.role = turn move = tablut.search_move(minmax_depth) after = time()
assert not move is None, "WHAT DO YOU MEAN MOVE IS NONE???"
_from, _to = move[0], move[1]
new_board = tablut.board.apply_move(_from, _to, turn)
tablut.board = new_board
print(f"Move: {move[0]} -> {move[1]}") print(f"Found in: {(after - before):.3f} s")
print("Resulting board:") tablut.board.print_grid() ui.draw(tablut.board)
if done: break
# sleep(1)
print("#####################################") print(f"GAME OVER ({i + 1} turns)") tablut.board.print_grid()
def quit_game(connection, exit_code=0, msg=""): """ Simple function to handle quitting, both with a proper game over and in case of errors
:param connection: Connection object (to be closed before quitting) :param exit_code: Program exit code (default 0) :param msg: Optional additional message to be printed (ideally, winning player if exit_code==0 and error message if exit_code!=0 - default "") """
if not msg in ["WHITE", "BLACK"] and msg != "": print(msg) elif exit_code == 0: print(f"{msg} wins") else: print(f"FAILURE - {errors[exit_code]}")
print("GAME OVER")
connection.close()
sys.exit(exit_code)
def main(): ic.disable()
role, ip, port, skip_conn, minmax_depth, max_turns = parse_arguments() opponent = "BLACK" if role == "WHITE" else "WHITE"
print(f"##################################### {CLIENT_NAME} TABLUT CLIENT") print(f"Role: {role}") print(f"Minmax depth: {minmax_depth}") print(f"Run locally? {skip_conn}")
print("#####################################")
if not skip_conn: print(f"IP address: {ip}") print(f"TCP port: {port}")
conn = Connection(CLIENT_NAME, role, server_ip=ip, server_port=port)
print("Connecting to server...", end="", flush=True) if not conn.connect_to_server(): quit_game(conn, exit_code=FAILED_CONN_ERR) else: print("Connected")
tablut = Tablut(role)
print("Waiting for sync...", end="", flush=True) if not conn.receive_new_state(): quit_game(conn, exit_code=FAILED_SYNC_ERR)
print("Received") print("STARTING GAME")
print("#####################################")
i = 0 while True: # WHITE plays on even turns, BLACK on odd turn = "WHITE" if i % 2 == 0 else "BLACK" print(f"----------{turn} [{'me' if turn == role else 'opponent'} - turn #{i}]")
if turn == role: tablut.board.print_grid(title="Current board:")
print("Searching move...")
before = time() move = tablut.search_move(minmax_depth) print(move) after = time()
f, t = move tablut.board = tablut.board.apply_move(f, t, role)
print(f"found: {f} -> {t}") print(f"search took: {(after - before):.3f} s")
tablut.board.print_grid(title="Updated board:") print("Sending move...", end="", flush=True)
# Did you manage to send the move? try: conn.send_move(f, t) print(f"sent") except BrokenPipeError: quit_game(conn, exit_code=BROKEN_PIPE_ERR) except ConnectionResetError: quit_game(conn, exit_code=CONN_RESET_ERR) ##########
elif turn == opponent: print("Waiting for opponent move...", end="", flush=True) received = None
# Did you receive the next game state? try: received = conn.receive_new_state() # Having to do this is kinda gay ngl while ic(received[1]) == opponent: received = conn.receive_new_state()
print(f"received") except ConnectionError: quit_game(conn, exit_code=STATE_UPDATE_ERR) except TimeoutError: quit_game(conn, exit_code=CONN_TIMEOUT_ERR) ##########
new_state, next_turn = received
# Did someone just win? if ic(next_turn) in ["WHITEWIN", "BLACKWIN"]: quit_game(conn, msg=str(next_turn).removesuffix("WIN")) ##########
tablut.board.update_state(new_state) tablut.board.print_grid(title="Updated board received:")
i += 1 else: run_locally(role, opponent, max_turns, minmax_depth)
return 0
if __name__ == "__main__": sys.exit(main())