def maximize(self, board, depth = 0): moves = board.get_available_moves() moves_boards = [] for m in moves: m_board = board.clone() m_board.move(m) moves_boards.append((m, m_board)) max_utility = (float('-inf'),0,0,0) best_direction = None for mb in moves_boards: if DEBUG: print('Testing %s at depth %d:' % (dirs[mb[0]], depth)) print_board(mb[1]) utility = self.chance(mb[1], depth + 1) if utility[0] >= max_utility[0]: max_utility = utility best_direction = mb[0] self.states_visited += 1 return best_direction, max_utility
def run_game(self): game_over = False rewards = None while not game_over: helpers.print_board(self.board) rewards = self.run_step() if rewards is not None: game_over = True return rewards
def __init__(self): self.board = GameBoard() self.ai = Expectimax() self.init_game() print_board(self.board) self.run_game() self.over = False
def n_queens(board, n, col, dao): if col >= n: board.increment_solutions_counter() h.print_board(board) h.save_board(board, dao) return True for row in range(n): if board.is_safe_box(row, col): board.set_queen_on_board(row, col) n_queens(board, n, col + 1, dao) board.remove_queen_on_board(row, col) return False
def main(): print('------------------------------') print('Checkers - legend:') print('_ - empty field') print('P1 - player1\'s piece') print('P2 - player2\'s piece') print('K1 - player1\'s king') print('K2 - player2\'s king') print('------------------------------') board = Board() print('Initial board state:') print_board(board) run_game(board)
def super_easy_solution_flow(boards_list, rows, cols, block_rows, block_cols, grid): for board in boards_list: board = elimination.elimination_technique(board, rows, cols, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) all_merge_intersection(boards_list[0], boards_list[1], boards_list[2], boards_list[3], boards_list[4]) check_board_1 = helpers.check_solution(boards_list[0], rows, cols, block_rows, block_cols) check_board_2 = helpers.check_solution(boards_list[1], rows, cols, block_rows, block_cols) check_board_3 = helpers.check_solution(boards_list[2], rows, cols, block_rows, block_cols) check_board_4 = helpers.check_solution(boards_list[3], rows, cols, block_rows, block_cols) check_board_5 = helpers.check_solution(boards_list[4], rows, cols, block_rows, block_cols) return (check_board_1, check_board_2, check_board_3, check_board_4, check_board_5)
def main(): parallel_games = 2 rounds = 30 if len(sys.argv) >= 2 and sys.argv[1]: rounds = int(sys.argv[1]) boards, links, scores = reset(parallel_games) times = [] finished_games = np.zeros(parallel_games, dtype=bool) for gid in range(parallel_games): for i in range(rounds): if not finished_games[gid]: start = timer() boards[gid], links[gid], scores[gid], finished_games[gid] \ = next_round(boards[gid], links[gid], scores[gid]) times.append(timer() - start) if config.PRINT_BOARDS and parallel_games < config.PRINT_THRESHOLD: h.print_board(boards[gid]) times = times[1:] # Exclude the first round to prevent the time the JIT compilation takes to falsify the stats total_time = 0 for i in range(len(times)): total_time += times[i] # ------------------------------------------------- STATS PRINTING ------------------------------------------------- if config.PRINT_STATS: stats_header = "Simulated " + h.bold(str(parallel_games)) + " games with a total of " + h.bold( str(parallel_games * rounds)) + " rounds." spaces = " " * int((103 - len(stats_header)) / 1.5) stats_header = spaces + stats_header + spaces print('\n' * 2) print(stats_header) print("-------------------------------------------------------------------------------------------------------") print("Total time: " + '\033[1m' + str(total_time * 1000) + " milliseconds" + '\033[0m') print("Average time per round: " + '\033[1m' + str(np.mean(times) * 1000 * 1000) + " microseconds" + '\033[0m') print("-------------------------------------------------------------------------------------------------------") print(" (All times exclude the first round to compensate for the JIT compiler)") print('\n' * 2)
def run_game(self): moves = 0 while True and moves < 2: move = self.ai.get_move(self.board) print("Player's Turn:", end="") self.board.move(move) print(dirs[move]) print_board(self.board) print("Computer's Turn") self.insert_random_tile() print_board(self.board) if len(self.board.get_available_moves()) == 0: print("GAME OVER (max tile): " + str(self.board.get_max_tile())) break moves += 1 if DELAY: time.sleep(DELAY)
def general_solution_flow(board, rows, cols, block_rows, block_cols, grid): count_general_loops = 0 count_to_heuristic_loops = 0 while (helpers.check_solution(board, rows, cols, block_rows, block_cols) == False and count_general_loops < 100): board = elimination.elimination_technique(board, rows, cols, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) if (helpers.check_solution(board, rows, cols, block_rows, block_cols)): return True board = only_choice.all_only_choices(board, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) if (helpers.check_solution(board, rows, cols, block_rows, block_cols)): return True count_to_heuristic_loops += 1 if (count_to_heuristic_loops > 10): board = heuristic.heuristic_technique(board, rows, cols, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) if (helpers.check_solution(board, rows, cols, block_rows, block_cols)): return True count_general_loops += 1 return False
def main(): if len(sys.argv) > 1: board_no = int(sys.argv[1]) else: board_no = random.randint(0, 49) print('puzzle no: ', board_no) boards = read_boards() grid = get_grid(boards, board_no) board = Board(grid) start_time = datetime.now() print_board(board) print('solving...') solve_board(board) end_time = datetime.now() time_diff = (end_time - start_time) # .strftime('%H:%M:%S') print('Solved in ' + str(time_diff))
def solve_board(bo): next_empty = find_next_empty(bo) if not next_empty: print_board(bo) return True else: row, col = next_empty # try all numbers for testVal in range(1, 10): if is_valid_placement(bo, testVal, row, col): # update board with new valid value bo.set_cell(testVal, row, col) # check if board is solved if solve_board(bo): return True bo.set_cell(x, row, col) return False
def main(): game = board.GameState.new_game() bots = {Player.x: RandomBot(), Player.o: RandomBot()} while not game.is_over(): time.sleep(0.3) print_board(game.board) bot_move = bots[game.next_player].select_move(game) game = game.apply_move(bot_move) if game.is_over(): print_board(game.board) winner = game.winner() winner_str = '' if winner is Player.x: winner_str = 'X' elif winner is Player.o: winner_str = 'O' else: winner_str = 'no one, it\'s a draw!' print('Winner is ' + winner_str)
def run_game(board): players = board.players is_move_possible_minimax, is_move_possible_alpha_beta = True, True move = 0 while is_move_possible_minimax and is_move_possible_alpha_beta: print('MOVE', move) is_move_possible_minimax = move_piece_alpha_beta(board, players[0]) print('\nAfter minimax move board:') print_board(board) if not is_move_possible_minimax: break is_move_possible_alpha_beta = move_piece_alpha_beta(board, players[1]) print('\nAfter alpha-beta move board:') print_board(board) move += 1 print('is_move_possible_minimax', is_move_possible_minimax) print('is_move_possible_alpha_beta', is_move_possible_alpha_beta) print('\nFinal board state:') print_board(board)
def general_solution_flow(boards_list, rows, cols, block_rows, block_cols, grid): count = 0 while(count < 4): for board in boards_list: board = elimination.elimination_technique(board, rows, cols, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) board = only_choice.all_only_choices(board, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) board = heuristic.heuristic_technique(board, rows, cols, block_rows, block_cols) helpers.print_board(board, rows, cols, grid) all_merge_intersection(boards_list[0], boards_list[1], boards_list[2], boards_list[3], boards_list[4]) count += 1 check_board_1 = helpers.check_solution(boards_list[0], rows, cols, block_rows, block_cols) check_board_2 = helpers.check_solution(boards_list[1], rows, cols, block_rows, block_cols) check_board_3 = helpers.check_solution(boards_list[2], rows, cols, block_rows, block_cols) check_board_4 = helpers.check_solution(boards_list[3], rows, cols, block_rows, block_cols) check_board_5 = helpers.check_solution(boards_list[4], rows, cols, block_rows, block_cols) return (check_board_1, check_board_2, check_board_3, check_board_4, check_board_5)
def prepare_board(boards_string, rows, cols, elements_string, grid): board = helpers.create_dict_representation(boards_string, rows, cols) helpers.fill_all_dot_cells(board, rows, cols, elements_string) print('=====>> Board With all The Possibilities <<=====\n') helpers.print_board(board, rows, cols, grid) return board
return True if find_path(board, row, col - 1, count): helpers.indent_print(count, 'left') return True if find_path(board, row - 1, col, count): helpers.indent_print(count, 'up') return True board[row][col] = previous helpers.indent_print(count, 'dead end') return False ''' a = find_path(board,row,col+1) b = find_path(board,row+1,col) c = find_path(board,row,col-1) d = find_path(board,row-1,col) if not (a or b or c or d): board[row][col]=previous return False ''' board = helpers.get_board('board.txt') helpers.print_board(board) print('-' * 50) find_path(board, 0, 0, 0) print('-' * 50) helpers.print_board(board)
def show(self): fig = plt.figure(1) helpers.print_board(self.board) plt.title("Reward = {}".format(self.score)) fig.canvas.draw() # updates plot
def simulation(game_, num_simulations, setup_0=None, setup_1=None, show_game=False): """ Simulate num_simulations many games of the agent of type agent_type_0 against the agent of type agent_type_1. If setup_0 or setup_1 are provided respectively, then take the pieces setup from those. If show_game is True, the game will be printed by the internal function. :param game_: game object that runs the simulation :param num_simulations: integer number of games to simulate :param setup_0: (optional) numpy array of the setup of agent 0 :param setup_1: (optional) numpy array of the setup of agent 1 :param show_game: (optional) boolean, whether to show the game or not :return: None, writes results to a file named after the agents acting """ blue_won = 0 blue_wins_bc_flag = 0 blue_wins_bc_noMovesLeft = 0 red_won = 0 red_wins_bc_flag = 0 red_wins_bc_noMovesLeft = 0 rounds_counter_per_game = [] rounds_counter_win_agent_0 = [] rounds_counter_win_agent_1 = [] game_times_0 = [] game_times_1 = [] types = game_.types_available for simu in range(num_simulations): # simulate games # reset setup with new setup if none given if setup_0 is not None: setup_agent_0 = setup_0 else: setup_agent_0 = draw_random_setup(types, 0, game_.game_dim) if setup_1 is not None: setup_agent_1 = setup_1 else: setup_agent_1 = draw_random_setup(types, 1, game_.game_dim) game_.agents[0].setup = setup_agent_0 game_.agents[1].setup = setup_agent_1 game_.reset() agent_output_type_0 = str(game_.agents[0]) agent_output_type_1 = str(game_.agents[1]) agent_output_type_0 = re.search('agent.(.+?) object', agent_output_type_0).group(1) agent_output_type_1 = re.search('agent.(.+?) object', agent_output_type_1).group(1) game_time_s = timer() if (simu + 1) % 1 == 0: print('{} won: {}, {} won: {}, Game {}/{}'.format( agent_output_type_0, red_won, agent_output_type_1, blue_won, simu, num_simulations)) print( '{} won by flag capture: {}, {} won by moves: {}, Game {}/{}'. format(agent_output_type_0, red_wins_bc_flag, agent_output_type_0, red_wins_bc_noMovesLeft, simu, num_simulations)) print( '{} won by flag capture: {}, {} won by moves: {}, Game {}/{}'. format(agent_output_type_1, blue_wins_bc_flag, agent_output_type_1, blue_wins_bc_noMovesLeft, simu, num_simulations)) print("Game number: " + str(simu + 1)) for step in range(2000): if show_game: helpers.print_board(game_.board) game_reward = game_.run_step() if game_reward is not None: if game_reward[0] == 1: # count wins game_times_0.append(timer() - game_time_s) red_won += 1 red_wins_bc_flag += 1 rounds_counter_win_agent_0.append(game_.move_count) elif game_reward[0] == 2: game_times_0.append(timer() - game_time_s) red_won += 1 red_wins_bc_noMovesLeft += 1 rounds_counter_win_agent_0.append(game_.move_count) elif game_reward[0] == -1: game_times_1.append(timer() - game_time_s) blue_won += 1 blue_wins_bc_flag += 1 rounds_counter_win_agent_1.append(game_.move_count) else: game_times_1.append(timer() - game_time_s) blue_won += 1 blue_wins_bc_noMovesLeft += 1 rounds_counter_win_agent_1.append(game_.move_count) rounds_counter_per_game.append(game_.move_count) break if show_game: helpers.print_board(game_.board) file = open( "{}_vs_{}_with_{}_sims.txt".format(agent_output_type_0, agent_output_type_1, num_simulations), "w") file.write("Statistics of {} vs. {} with {} games played.\n".format( agent_output_type_0, agent_output_type_1, num_simulations)) file.write( "Overall computational time of simulation: {} seconds.\n".format( sum(game_times_0) + sum(game_times_1))) file.write("\nAgent {} won {}/{} games (~{}%).\n".format( agent_output_type_0, red_won, num_simulations, round(100 * red_won / num_simulations, 2))) file.write( "Reasons for winning: {} flag captures, {} wins through killing all enemies\n" .format(red_wins_bc_flag, red_wins_bc_noMovesLeft)) file.write("\nAgent {} won {}/{} games (~{}%).\n".format( agent_output_type_1, blue_won, num_simulations, round(100 * blue_won / num_simulations, 2))) file.write( "Reasons for winning: {} flag captures, {} wins through killing all enemies\n" .format(blue_wins_bc_flag, blue_wins_bc_noMovesLeft)) file.write("\nAverage game duration overall: {} rounds\n".format( round(sum(rounds_counter_per_game) / num_simulations), 2)) file.write("Maximum number of rounds played: {} rounds\n".format( max(rounds_counter_per_game))) file.write("Minimum number of rounds played: {} rounds\n".format( min(rounds_counter_per_game))) file.write("\nAverage game duration for {} wins: {} rounds\n".format( agent_output_type_0, round( sum(rounds_counter_win_agent_0) / len(rounds_counter_win_agent_0)), 2)) file.write("Maximum number of rounds played: {} rounds\n".format( max(rounds_counter_win_agent_0))) file.write("Minimum number of rounds played: {} rounds\n".format( min(rounds_counter_win_agent_0))) file.write("\nAverage game duration for {} wins: {} rounds\n".format( agent_output_type_1, round( sum(rounds_counter_win_agent_1) / len(rounds_counter_win_agent_1)), 2)) file.write("Maximum number of rounds played: {} rounds\n".format( max(rounds_counter_win_agent_1))) file.write("Minimum number of rounds played: {} rounds\n".format( min(rounds_counter_win_agent_1))) file.write("\nAverage computational time for {} wins: {} seconds\n".format( agent_output_type_1, sum(game_times_1) / len(game_times_1))) file.write("Maximum computational time: {} seconds\n".format( max(game_times_1))) file.write("Minimum computational time: {} seconds\n".format( min(game_times_1))) file.write("\nAverage computational time for {} wins: {} seconds\n".format( agent_output_type_0, sum(game_times_0) / len(game_times_0))) file.write("Maximum computational time: {} seconds\n".format( max(game_times_0))) file.write("Minimum computational time: {} seconds\n".format( min(game_times_0))) file.close() return