def evaluate(show=False): score = 0 won = 0 scores = [] for i in range(N_evaluate): newscore, won_bool = gameplay.play(show=show, minefield_param=MINEFIELD_PARAM) scores.append(newscore) if newscore == -1: score *= (float(N_evaluate) / np.maximum(1, i)) won *= (float(N_evaluate) / np.maximum(1, i)) break if won_bool: won += 1 score += newscore if i % 10 == 0: sys.stdout.write("\r{}/{}".format(i, N_evaluate)) sys.stdout.flush() np.savetxt('scores0.out.csv', scores, delimiter=',') sys.stdout.write("\r{}/{}\n".format(N_evaluate, N_evaluate)) sys.stdout.flush() return (float(score) / N_evaluate, float(won) / N_evaluate)
def play_game(board, board_file_name, player_set, max_moves=np.Infinity, timing=None, game_type="Game", round=None, tourn_name=""): """ Play a game of The Crown under the conditions given, returning end result. Arguments: board (Board): The board position to play. board_file_name (str): Full path to the the board. player_set (list): A list with two dictionaries with white's and black's playing parameters, e.g.: "name": "Crowny III" "type": "machine" "ranking": 1500 "play method": "minimax" "max_depth": 3 "max_check_quiesc_depth": 8 "transposition_table": True "killer_moves": True "iterative_deepening": True "randomness": 0 "file_name": "crowny-iii" "file": full path to player's .yaml file. max_moves (int): The maximum number of moves to play. timing (int): None = no time limit; TODO: Define and implement: "move" = time limit per move. "game" = total time limit for the game. game_type (str): Type of game played {"Game", "Match"}. round (int): Number of round between these players. tourn_name (str): Name of the tournament (e.g. "I_Crown_Tournament") Returns: str: gp.TXT_DRAW, gp.TXT_WHITE_WINS or gp.TXT_BLACK_WINS int: gp.ON_GOING, gp.VICTORY_CROWNING, gp.VICTORY_NO_PIECES_LEFT, gp.DRAW_NO_PRINCES_LEFT, gp.DRAW_STALEMATE, gp.DRAW_THREE_REPETITIONS, gp.PLAYER_RESIGNS str: 'rec_file_path', full path to the game moves. str: 'metrics_file_path', full path to the game metrics file. """ # Define .txt output files. dir_path = os.path.dirname(os.path.realpath(__file__)) rand_0 = None if player_set[0]["type"] == "human" \ else player_set[0]["randomness"] rand_1 = None if player_set[1]["type"] == "human" \ else player_set[1]["randomness"] rec_file_name = create_rec_file_name(game_type, player_set[0]["name"], rand_0, player_set[1]["name"], rand_1, round, tourn_name) rec_file_path = f"{dir_path}{OUTPUT_PATH}{rec_file_name}" metrics_file_path = f"{dir_path}{OUTPUT_PATH}{GAME_METRICS_FILE}" # Start the game! with open(rec_file_path, "a") as rec_file: move_number = display_start(board, player_set, board_file_name, rec_file) # Initialize game variables. game_end = False player_quit = False max_moves_played = False end_status = gp.ON_GOING game_trace = gp.Gametrace(board) # Initialize one transposition table and killer moves list per side. t_table = [gp.Transposition_table(), gp.Transposition_table()] killer_list = [gp.Killer_Moves(), gp.Killer_Moves()] # Main game loop. while not game_end: # Main loop of the full game. board.print_char() if player_set[board.turn]["type"] == MACHINE_PLAYER: # A MACHINE plays this side. move, result, game_end, end_status, time_used, tt_metrics =\ gp.play( board, params=player_set[board.turn], trace=game_trace, t_table=t_table[board.turn], killer_list=killer_list[board.turn] ) # Print move metrics. with open(metrics_file_path, "a") as metrics_file: display_move_metrics(board.turn, move, result, player_set[board.turn], time_used, tt_metrics, game_trace, metrics_file) else: # A HUMAN plays this side. move, result = request_human_move(board) if result is not None: # Non-void value signals end. player_quit = True game_end = True # Update outputs after move. if not game_end: # Update board with move. coord1, coord2 = move _, _, _ = board.make_move(coord1, coord2) # Check if the move just made ends the game. _, _, aftermove_game_end, after_move_game_status = \ gp.evaluate_terminal(board, 0) if aftermove_game_end: # The move made ended the game. game_end = True end_status = after_move_game_status else: # Update game trace. TODO: include irreversible arg. repetition = game_trace.register_played_board(board) # Print move in game log. move_number = display_move(board, move, move_number, rec_file) if repetition: # Draw; end of game. game_end = True result = gp.DRAW end_status = gp.DRAW_THREE_REPETITIONS else: # Draw separation line. print('.' * 80) if game_end: # End of the game. if player_quit: # Human chose to quit. result = gp.OPPONENT_WINS end_status = gp.PLAYER_RESIGNS display_quit_results(board, rec_file) elif max_moves_played: # Max. number of moves requested reached. end_status = gp.ON_GOING else: # The game reached a natural end. print('.' * 80) board.print_char() display_end_results(board, result, end_status, rec_file) # Update moves count. max_moves -= 1 if max_moves == 0: game_end = True max_moves_played = True # Result of the game. if result == gp.DRAW: game_result_txt = gp.TXT_DRAW elif result == gp.PLAYER_WINS: if board.turn == bd.WHITE: game_result_txt = gp.TXT_WHITE_WINS else: game_result_txt = gp.TXT_BLACK_WINS else: if board.turn == bd.WHITE: game_result_txt = gp.TXT_BLACK_WINS else: game_result_txt = gp.TXT_WHITE_WINS return game_result_txt, end_status, rec_file_path, metrics_file_path
# -*- coding: utf-8 -*- """ Pleay Chinese checker game Human vs Computer @author: Sean, Bill and Alexandra """ import gameplay as g import cchecker import agent from agent.dumb import DumbAgent from agent.alphabeta import AlphaBetaAgent from agent.MCTS import MCTS if __name__ == '__main__': print(cchecker.welcomemsg()) p1side = cchecker.Player.white p2side = cchecker.Player.black player1 = g.GamePlayer(p1side, g.PlayerType.human, agent.Agent()) player2 = g.GamePlayer(p2side, g.PlayerType.computer, DumbAgent()) # player2 = g.GamePlayer(p2side, g.PlayerType.computer, AlphaBetaAgent()) # player2 = g.GamePlayer(p2side, g.PlayerType.computer, MCTS()) result = g.play(player1, player2, cchecker.GameState, cchecker.interface) cchecker.gameend(result)
factor = width // gameplay.cellSizes[0] screen = pygame.display.set_mode((width, height)) loadFiles() clock = pygame.time.Clock() done = False pygame.mixer.init() pygame.mixer.music.load("music/soundtrack.wav") pygame.mixer.music.play(-1) #time.sleep(0.1) while not done: for event in pygame.event.get(): gameplay.onPress(event, screen) if (event.type == pygame.QUIT or gameplay.isOpen == False): done = True gameplay.play(screen) clock.tick(60) pygame.display.flip()
messagebox.showinfo('Game Over', f'{result} WON') flag = False return flag # Start Game pygame.init() running = True flag = True # Screen screen = pygame.display.set_mode((900, 900)) pygame.display.set_caption("Tic-Tac-Toe") icon = pygame.image.load('icon.png') pygame.display.set_icon(icon) # Game Loop while running: pygame.display.update() draw_board(screen) flag = display_winner(flag) play() draw_all_shapes(screen) time.sleep(0.3) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
# -*- coding: utf-8 -*- """ Play Hexapwn in a dumb way @author: seanxiong """ import gameplay as g import hexapwn import agent from agent.dumb import DumbAgent if __name__ == '__main__': print(hexapwn.welcomemsg()) p1side = hexapwn.Player.white p2side = hexapwn.Player.black player1 = g.GamePlayer(p1side, g.PlayerType.human, agent.Agent()) player2 = g.GamePlayer(p2side, g.PlayerType.computer, DumbAgent()) result = g.play(player1, player2, hexapwn.GameState, hexapwn.interface) hexapwn.gameend(result)