コード例 #1
0
def run_game(game_class=Game2048, title='2048!', data_dir='save'):
    '''
  This function will run the 2048 game for one-AI-player 
  '''

    # Initialize game using py_game package
    pygame.init()
    pygame.display.set_caption(title)
    pygame.display.set_icon(game_class.icon(32))
    clock = pygame.time.Clock()

    # Created the directory to save the gmae grid and max score
    os.makedirs(data_dir, exist_ok=True)

    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    # screen = pygame.display.set_mode((50, 20))
    manager = GameManager(Game2048, screen,
                          os.path.join(data_dir, '2048.score'),
                          os.path.join(data_dir, '2048.%d.state'))

    # This will faster the animation
    manager.game.ANIMATION_FRAMES = 1
    manager.game.WIN_TILE = 999999

    tick = 0
    running = True

    # 2048 Game loop
    while running:
        clock.tick(120)
        tick += 1

        if tick % 5 == 0:
            old_grid = deepcopy(manager.game.grid)

            # Use Minimax algorithm to decide best possible move
            best_move, best_score = maximize(old_grid)

            if best_move is None:
                print('No way! Maximum number is %s' %
                      np.max(manager.game.grid))
                break

            #print(best_move)
            e = EVENTS[best_move]
            manager.dispatch(e)
            ##pprint(manager.game.grid, width=30)
            ##print(manager.game.score)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONUP:
                manager.dispatch(event)

        manager.draw()

    pygame.quit()
    manager.close()
コード例 #2
0
def run_game(game_class=Game2048, title='2048!', data_dir='save'):
    pygame.init()
    pygame.display.set_caption(title)
    pygame.display.set_icon(game_class.icon(32))
    clock = pygame.time.Clock()

    os.makedirs(data_dir, exist_ok=True)

    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    # screen = pygame.display.set_mode((50, 20))
    manager = GameManager(Game2048, screen,
                          os.path.join(data_dir, '2048.score'),
                          os.path.join(data_dir, '2048.%d.state'))

    # faster animation
    manager.game.ANIMATION_FRAMES = 1
    manager.game.WIN_TILE = 999999

    # game loop
    tick = 0
    running = True

    while running:
        clock.tick(120)
        tick += 1

        if tick % 5 == 0:
            old_grid = deepcopy(manager.game.grid)

            best_action, best_score = maximize(old_grid)

            if best_action is None:
                print('No way! Maximum number is %s' %
                      np.max(manager.game.grid))
                break

            print(best_action)
            e = EVENTS[best_action]
            manager.dispatch(e)
            pprint(manager.game.grid, width=30)
            print(manager.game.score)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONUP:
                manager.dispatch(event)

        manager.draw()
    # end while

    pygame.quit()
    manager.close()
コード例 #3
0
def run_game(game_class=Game2048, title='2048!', data_dir='save'):
    '''
  This will run a traditional one-human-player 2048 game
  '''
    pygame.init()
    pygame.display.set_caption(title)
    pygame.display.set_icon(game_class.icon(32))
    clock = pygame.time.Clock()

    os.makedirs(data_dir, exist_ok=True)

    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    manager = GameManager(Game2048, screen,
                          os.path.join(data_dir, '2048.score'),
                          os.path.join(data_dir, '2048.%d.state'))

    # game loop
    running = True

    while running:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break

            manager.dispatch(event)

        manager.draw()
    # end while

    pygame.quit()
    manager.close()
コード例 #4
0
ファイル: batch_main.py プロジェクト: ant6si/2048_sh
def play_game(f_handler, game_class=Game2048, title='2048!', data_dir='save'):
    """
    play game until the game is over, and save the board state as episode
    f_handler: feature set
    """
    #def play_game(queue, f_handler, game_class=Game2048, title='2048!', data_dir='save'):
    # print("data_path: {}".format(data_dir))
    board_chain = []
    reward_chain = []
    final_score = 0
    pygame.init()
    pygame.display.set_caption(title)
    pygame.display.set_icon(game_class.icon(32))
    clock = pygame.time.Clock()
    os.makedirs(data_dir, exist_ok=True)
    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    # screen = pygame.display.set_mode((50, 20))
    manager = GameManager(Game2048, screen,
                          os.path.join(data_dir, '2048.score'),
                          os.path.join(data_dir, '2048.%d.state'))
    # faster animation
    manager.game.ANIMATION_FRAMES = 1
    manager.game.WIN_TILE = 999999
    # game loop
    tick = 0
    running = True
    count = 0
    while running:
        clock.tick(2000)
        tick += 1
        if tick % 2 == 0:
            # t1 = time.time()
            count += 1
            #print("count: {}".format(count))
            old_grid = deepcopy(manager.game.grid)
            print(old_grid)
            old_score = manager.game.score
            best_action, best_score, moved_grid = findBestMove(
                old_grid, f_handler)
            board_chain.append(moved_grid)
            # t2 = time.time()
            if best_action is None:
                final_score = manager.game.score
                reward = final_score - old_score
                assert reward == 0, "The last reward wasn't Zero"
                reward_chain.append(reward)
                #print('The end. \n Score:{} / Max num: {}'.format(manager.game.score, np.max(manager.game.grid)))
                break
            #print(best_action)
            e = EVENTS[best_action]
            manager.dispatch(e)
            new_score = manager.game.score
            reward = new_score - old_score
            reward_chain.append(reward)
            #pprint(manager.game.grid, width=30)
            #print(manager.game.score)
            # t3 = time.time()
            # print("Find best action: {}s , dispatch action: {}s".format(t2-t1, t3-t2))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONUP:
                manager.dispatch(event)

        manager.draw()
    episode = [board_chain, reward_chain, final_score]
    queue.put(episode)
    manager.close()
    pygame.quit()
    return final_score
コード例 #5
0
def play_game(game_class=Game2048, title='2048!', data_dir='save'):
    """
    play one game using with game agent
    :param game_class:
    :param title:
    :param data_dir:
    :return: final score
    :return max_tile
    """
    # print("data_path: {}".format(data_dir))
    final_score = 0
    max_tile = -1
    pygame.init()
    pygame.display.set_caption(title)
    pygame.display.set_icon(game_class.icon(32))
    clock = pygame.time.Clock()
    os.makedirs(data_dir, exist_ok=True)
    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    # screen = pygame.display.set_mode((50, 20))
    manager = GameManager(Game2048, screen,
                          os.path.join(data_dir, '2048.score'),
                          os.path.join(data_dir, '2048.%d.state'))
    # faster animation
    manager.game.ANIMATION_FRAMES = 1
    manager.game.WIN_TILE = 999999

    # game loop
    tick = 0
    running = True

    count = 0
    while running:
        clock.tick(120)
        tick += 1

        if tick % 2 == 0:
            count += 1
            #print("count: {}".format(count))
            old_grid = deepcopy(manager.game.grid)
            best_action, best_score, moved_grid = findBestMove(old_grid)

            if best_action is None:
                max_tile = np.max(old_grid)
                final_score = manager.game.score
                #print('The end. \n Score:{} / Max num: {}'.format(manager.game.score, np.max(manager.game.grid)))
                break

            #print(best_action)
            e = EVENTS[best_action]
            manager.dispatch(e)
            #pprint(manager.game.grid, width=30)
            #print(manager.game.score)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONUP:
                manager.dispatch(event)

        manager.draw()

    manager.close()
    return final_score, max_tile
コード例 #6
0
def play_game(game_class=Game2048, title='2048!', data_dir='save'):
    """
    play game and recieved action advice by game agent
    :param game_class:
    :param title:
    :param data_dir:
    :return:
    """
    # print("data_path: {}".format(data_dir))
    final_score = 0
    max_tile = -1
    pygame.init()
    pygame.display.set_caption(title)
    pygame.display.set_icon(game_class.icon(32))
    clock = pygame.time.Clock()
    os.makedirs(data_dir, exist_ok=True)
    screen = pygame.display.set_mode((game_class.WIDTH, game_class.HEIGHT))
    # screen = pygame.display.set_mode((50, 20))
    manager = GameManager(Game2048, screen,
                          os.path.join(data_dir, '2048.score'),
                          os.path.join(data_dir, '2048.%d.state'))
    # faster animation
    manager.game.ANIMATION_FRAMES = 1
    manager.game.WIN_TILE = 999999

    # game loop
    tick = 0
    running = True

    count = 0

    while running:
        clock.tick(120)
        tick += 1

        if tick % 4 == 0:
            count += 1
            #print("count: {}".format(count))
            old_grid = deepcopy(manager.game.grid)
            best_action, best_score, moved_grid = findBestMove(old_grid)

            if best_action is None:
                max_tile = np.max(old_grid)
                final_score = manager.game.score
                #print('The end. \n Score:{} / Max num: {}'.format(manager.game.score, np.max(manager.game.grid)))
                break

            #print(best_action)
            """check"""
            e = pygame.event.wait()
            e2 = pygame.event.wait()

            # 0 u /1 d/ 2 r/ 3 l urdl
            if not ('key' in e.dict):
                continue
            player_action = e.dict['key'] - 273
            if player_action == 1:
                player_action = 2
            if player_action == 2:
                player_action = 1
            player_grid, _, _ = move(old_grid, player_action)
            # print("action: ".format(player_action))
            # print("\n {}\m".format(player_grid))
            player_score = evaluation(player_grid)
            best_score = evaluation(moved_grid)
            diff_detail = get_diff_detail(player_grid, moved_grid)

            print("best action: {} / player action: {}".format(
                best_action, player_action))
            if (best_action == player_action):
                print("Good, I think the same Thing.")
            print("Player's score: {}".format(player_score))
            print("Best score: {}".format(best_score))
            diff = best_score - player_score
            #self.SC_2_big, self.SC_2_mono, self.HW_mergeable, self.HW_layer, self.HW_distinct, self.HW_empty
            print(
                "Diff: {} / Big: {} + Mono: {} + merge: {} + layer: {} + distinct: {} + empty: {}"
                .format(diff, diff_detail[0], diff_detail[1], diff_detail[2],
                        diff_detail[3], diff_detail[4], diff_detail[5]))
            if diff > advice_threshold:
                print("-----------Detected--------------")
                best_direction = get_dircetion_str(best_action)
                player_direction = get_dircetion_str(player_action)

                print(
                    "You wanted to move {}, but how about move to {}?".format(
                        player_direction, best_direction))
                advice = give_advice(diff_detail)
                print(advice)
                e = pygame.event.wait()
                e2 = pygame.event.wait()
                print("Action submitted.")
            print()

            #e = EVENTS[best_action]

            manager.dispatch(e)
            # time.sleep(0.1)
            #pprint(manager.game.grid, width=30)
            #print(manager.game.score)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONUP:
                manager.dispatch(event)

        manager.draw()

    manager.close()
    return final_score, max_tile