Example #1
0
    def user_control(self):
        while True:
            self.action = input("Enter a command or a number to train: ")
            # Test classification percentage using both the test set and training set
            if self.action[0] == "t":
                self.test_percentage_training_and_test_set()
            # Play forever
            elif self.action[0] == "s":
                self.results_length = float('inf')
                return
            # Play 50 games, using the neural net p or a random player r
            elif self.action[0] == "p" or self.action[0] == "r":
                self.results_length = 50
                return
            # Run the grading function
            elif self.action[0] == "c":
                if len(self.results_from_nn_playing) < 50:
                    self.results_length = 50
                    return
                else:
                    self.print_comparison()
            elif self.action[0] == "l":
                self.collect_cases = not self.collect_cases
                if self.collect_cases:
                    self.neural_network_cases = load_cases()
                    self.expectimax = Expectimax()
            else:
                self.errors = self.move_classifier.do_training(
                    epochs=int(self.action), errors=self.errors)
                self.test_percentage_training_and_test_set()

            print("Total time elapsed: " +
                  str(round((time() - self.start_time) / 60, 1)) + " min")
def get_strategy(strategy_type):
    if strategy_type == "minimax":
        return Minimax()
    elif strategy_type == "expectimax":
        return Expectimax()
    elif strategy_type == "simple":
        return Simple()
    else:
        return Random()
 def __init__(self):
     Frame.__init__(self)
     self.grid()
     self.master.title('Ganesh-2048')
     self.grid_cells = []
     self.initialise_grid()
     self.initilaise_matrix()
     self.update_grid_cells()
     self.AI = Expectimax()
     self.start_game()
     self.mainloop()
Example #4
0
 def start_game(self):
     print "avg", sum(self.results)/float(len(self.results) + 0.001)
     if len(self.results) < 30:
         self.game_board = Game2048(board=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])
         self.board = self.game_board.board
         self.game_board.generate_new_node()
         self.depth = 4
         self.move_count = 0
         self.expectimax = Expectimax()
         self.draw_board()
         self.time = time()
         self.run_algorithm()
     else:
         print self.results
         print "avg", sum(self.results)/float(len(self.results))
Example #5
0
 def __init__(self,
              collect_cases=False,
              use_merge_input_nodes=False,
              depth=3):
     self.collect_cases = collect_cases
     self.use_merge_input_nodes = use_merge_input_nodes
     self.depth = depth
     if collect_cases:
         self.neural_network_cases = load_cases()
         self.expectimax = Expectimax()
     self.results_from_nn_playing = []
     self.results_from_random_playing = []
     self.results = []
     self.results_from_random_playing = [112] * 50
     self.start_time = time()
     self.print_commands()
     self.setup_network()
     self.user_control()
     self.start_game()
Example #6
0
def run_game(game_class=Game2048, title='2048: In Python!', data_dir=None, **kwargs):
    pygame.init()
    pygame.display.set_caption(title)

    AI_type = kwargs["AI_type"]

    # Try to set the game icon.
    try:
        pygame.display.set_icon(game_class.icon(32))
    except pygame.error:
        # On windows, this can fail, so use GDI to draw then.
        print('Consider getting a newer card or drivers.')
        os.environ['SDL_VIDEODRIVER'] = 'windib'

    if data_dir is None:
        data_dir = user_data_dir(appauthor='Quantum', appname='2048', roaming=True)
        try:
            os.makedirs(data_dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

    score_file_prefix = os.path.join(data_dir, '2048')
    state_file_prefix = os.path.join(data_dir, '2048')

    if AI_type:
        score_file_prefix += '_' + AI_type
        state_file_prefix += '_' + AI_type

    if AI_type in ["heuristic", "rollout", "MCTS"]:
        if AI_type == "rollout" and kwargs["type"] is None or kwargs["type"] == 'None':
            type_str = "random"
        else:
            type_str = kwargs["type"]
        score_file_prefix += '_' + type_str
        state_file_prefix += '_' + type_str

    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    manager = GameManager(Game2048, screen,
                          score_file_prefix + '.score',
                          state_file_prefix + '.%d.state', **kwargs)
    if not AI_type:
        try:
            while True:
                event = pygame.event.wait()
                manager.dispatch(event)
                for event in pygame.event.get():
                    manager.dispatch(event)
                manager.draw()

        finally:
            pygame.quit()
            manager.close()

    else:
        try:
            pygame.event.set_blocked([pygame.KEYDOWN, pygame.MOUSEBUTTONUP])
            manager.new_game(**kwargs)
            game_scores = []
            best_tiles = []
            condition = True
            tree = None

            if AI_type in ["rollout", "MCTS"]:
                num_rollouts = kwargs["num_rollouts"]
                max_depth = kwargs["max_depth"]
                epsilon = kwargs["epsilon"]
                if epsilon < 0 or epsilon > 1:
                    raise ValueError("Epsilon must be in the interval [0, 1].")
                if AI_type == "MCTS":
                    UCT = kwargs["UCT"]
                    tree = AI.GameTree(np.array(manager.game.grid), max_search_depth=max_depth,
                                       num_rollouts=num_rollouts, epsilon=epsilon, UCT=UCT,
                                       use_expert_score=kwargs["use_expert"])

            while condition:
                if manager.game.lost:
                    event = pygame.event.Event(pygame.MOUSEBUTTONUP, {"pos": manager.game.lost_try_again_pos})
                    game_scores.append(manager.game.score)
                    best_tiles.append(np.max(manager.game.grid))
                    print(len(game_scores))
                    if AI_type in ["random", "heuristic", "MCTS", "rollout", "expectimax"]:
                        condition = kwargs["num_games"] > len(game_scores)
                elif manager.game.won == 1:
                    event = pygame.event.Event(pygame.MOUSEBUTTONUP, {"pos": manager.game.keep_going_pos})
                elif AI_type == "random":
                    event = AI.random_move_event(np.array(manager.game.grid))
                elif AI_type == "heuristic":
                    event = AI.heuristic_move_event(np.array(manager.game.grid), kwargs["type"])
                elif AI_type == "rollout":
                    event = AI.rollouts(np.array(manager.game.grid), manager.game.score, kwargs["type"],
                                        max_search_depth=max_depth, num_rollouts=num_rollouts, epsilon=epsilon,
                                        use_expert_score=kwargs["use_expert"])
                elif AI_type == "MCTS":
                    event = tree.MCTS(np.array(manager.game.grid), manager.game.score)
                elif AI_type == "expectimax":
                    event = Expectimax(kwargs['max_depth']).get_best_move(np.array(manager.game.grid))
                else:
                    raise ValueError("AI mode selected but invalid AI type was supplied!")
                manager.dispatch(event)
                manager.draw()

            print("Number of games played:", len(game_scores))
            print("Game Scores:")
            print(game_scores)
            print("Best Tiles:")
            print(best_tiles)
            print("Max Score:", max(game_scores))
            print("Max Tile:", max(best_tiles))
            print("Average Score:", stats.mean(game_scores))

        finally:
            if "simulate" not in kwargs:
                pygame.quit()
                manager.close()

        if "simulate" in kwargs:
            results = {
                "game_scores": game_scores,
                "best_tiles": best_tiles,
                "max_score": max(game_scores),
                "max_tile": max(best_tiles),
                "avg_score": stats.mean(game_scores)
            }
            return results