Exemple #1
0
    def __init__(self, host_ip, port_number, config):
        self.host = host_ip
        self.port = port_number
        self.config = config

        if "use_maps?" in config and config["use_maps?"]:
            config["board_dimensions"] = (len(config["object_map"][0]),
                                          len(config["object_map"]))
            config["bomb_coordinates"], config["goal_coordinates"], config[
                "obstacle_coordinates"] = [], [], []
            config["weights"] = {}
            for row_index, row in enumerate(config["object_map"]):
                for char_index, char in enumerate(row):
                    if char == "O":
                        config["obstacle_coordinates"].append(
                            (char_index, row_index))
                    elif char == "I":
                        config["obstacle_coordinates"].append(
                            (char_index, row_index, "invisible"))
                    elif char == "B":
                        config["bomb_coordinates"].append(
                            (char_index, row_index))
                    elif char == "G":
                        config["goal_coordinates"].append(
                            (char_index, row_index))
                    elif char == "A":
                        config["start_position"] = (char_index, row_index)

                for char_index, char in enumerate(
                        config["weight_map"][row_index]):
                    if char in "1234":
                        config["weights"][
                            str(char_index) + "," +
                            str(row_index)] = config["weight_dictionary"][char]

        # Size of the world ...
        print("Starting the Game Board")
        columns, rows = config["board_dimensions"]

        self.root = tk.Tk()

        # Create gameboard
        self.board = gb.GameBoard(self.root, self.config, columns, rows)
        self.board.pack(side="top", fill="both", expand="true", padx=4, pady=4)

        # Initialize the weights ...
        self.initialize_weights()

        self.initialize_obstacles()
        self.initialize_goals()
        self.initialize_bombs()

        self.player = gb.Player('player', *self.config["start_position"],
                                'south', 'front', self.config)
        self.player.set_home((0, 0))
        self.player.close_eyes()

        # Add player ...
        self.board.add(self.player, *self.config["start_position"])
        self.root.update()
def start_game():
    move_number = 1

    game_board = board.GameBoard()

    board_ui = user_ui.BoardOnScreen()
    board_ui.init_board_ui()

    player = [pl.HumanPlayer(), pl.HumanPlayer()]

    while True:
        active_player = get_active_player(move_number)

        move = None
        while move is None:
            current_move = player[active_player].make_move(game_board.get_board())
            if game_board.is_valid_move(current_move):
                move = current_move

        game_board.update_board(move, active_player)
        board_ui.draw(game_board.get_board())
        game_status = game_board.get_board_state()

        if game_status.game_state > const.GAME_IN_PROGRESS:
            board_ui.draw_winner(game_status)

        move_number += 1

        for event in pg.event.get():
            if event.type == pg.KEYDOWN:
                pg.quit()
                quit()
Exemple #3
0
def battle_start(times, first_agent, second_agent):
    progress_bar = tqdm.tqdm(total=times)
    count = [0, 0, 0]
    for index in range(0, times):
        game = game_board.GameBoard(first_agent, second_agent)
        game_result = game.game_start()[0] + 1
        if game_result == 3:
            game_result = 1
        count[game_result] += 1
        progress_bar.update(1)
    progress_bar.close()
    output_match_result(times, count, first_agent, second_agent)
Exemple #4
0
    def init(self):
        self.board = pygame.image.load("im&font/board.png")
        
        #Initiate the sprites
        self.cells = game_board.GameBoard()
                
#        self.sel_cell=pygame.sprite.GroupSingle()
        
        self.turn = random.choice([1,2])
        self.finish = False
        self.result = ''
        self._init = 0
 def game_board_fixture(self):
     game_board_fixture = game_board.GameBoard(3)
     game_board_lists = [None] * 3
     game_board_lists[0] = ["01", "02", "03"]
     game_board_lists[1] = ["04", "05", "06"]
     game_board_lists[2] = ["07", "08", "09"]
     game_board_details = [None] * 3
     game_board_details[0] = ["P", "NP", "S"]
     game_board_details[1] = ["NP", "P", "NP"]
     game_board_details[2] = ["NP", "NP", "P"]
     game_board_fixture.game_board_lists = game_board_lists
     game_board_fixture.game_board_details = game_board_details
     return game_board_fixture
Exemple #6
0
 def __battle_all_agent(self):
     waiting_queue = []
     for index in range(0, self.__NUMBER_INDIVIDUALS):
         for times in range(0, self.__NUMBER_INDIVIDUALS):
             first = self.__now_generation[index][0].copy()
             second = self.__now_generation[times][0].copy()
             game = game_board.GameBoard(first, second)
             waiting_queue.append(self.__executor.submit(game.game_start, (index, times)))
     for end_task in concurrent.futures.as_completed(waiting_queue):
         self.__progress_bar.update(1)
         if end_task.result()[0] == -1:
             self.__now_generation[end_task.result()[1][0]][1] += 1
         elif end_task.result()[0] == 1:
             self.__now_generation[end_task.result()[1][1]][1] += 1
Exemple #7
0
    def setup(self):
        """
        All variables held here, so the game can be restarted in runtime.
        :param map: int
        :return: None
        """

        # Setup game map
        game_map = self.levels[random.randint(0, len(self.levels) - 1)]
        self.levels.remove(game_map)

        self.game_settings = global_variables.game_settings
        self.game_board = game_board.GameBoard(self.game_settings[game_map][0])
        self.screen = self.game_board.get_screen
        pygame.mixer.music.load('assets/sounds/music1.wav')
        pygame.mixer.music.set_volume(0.3)
        self.sound_you_lose = pygame.mixer.Sound('assets/sounds/youlose.wav')
        self.difficulty = 1
        self.game_state = 1  # 1 - Main Menu, 2 - Game started, 3 - You lose, 4 - You win
        self.wave = 2 * self.difficulty
        self.wave_number = 0
        self.wave_level = 1
        self.timer = time.time()
        self.game_map = game_map
        global_variables.stats_money = 36

        # Enemies
        pygame.time.set_timer(25, 1000)
        self.enemy_queue = []
        self.enemy_list = pygame.sprite.Group()
        self.enemy_spawn_position_x = global_variables.game_settings[game_map][
            2][0][0]
        self.enemy_spawn_position_y = global_variables.game_settings[game_map][
            2][0][1]

        # Towers
        self.towers_list = pygame.sprite.Group()
        self.moving_objects = pygame.sprite.Group()
        self.tower_available_positions = global_variables.game_settings[
            game_map][1]

        # Player
        self.player_health = global_variables.stats_player_health = 10 * self.difficulty

        # Effects
        pygame.time.set_timer(26, 2000)
        self.effects_list = pygame.sprite.Group()
        self.effects_list.add(effect.Effect(600, 400, 'FIRE'))

        self.positions = []
Exemple #8
0
 def __battle_random_agent(self):
     executor = concurrent.futures.ProcessPoolExecutor()
     for index in range(0, self.__NUMBER_INDIVIDUALS):
         waiting_queue = []
         for times in range(0, self.__NUMBER_BATTLES):
             first = self.__now_generation[index][0].copy()
             second = agent.RandomAgent()
             game = game_board.GameBoard(first, second)
             waiting_queue.append(executor.submit(game.game_start))
         for end_task in concurrent.futures.as_completed(waiting_queue):
             self.__progress_bar.update(1)
             if end_task.result() == -1:
                 self.__now_generation[index][1] += 2
             elif end_task.result() == 2:
                 self.__now_generation[index][1] += 1
     executor.shutdown()
Exemple #9
0
 def start(self, file_path, save_interval, first_agent, second_agent):
     self.__progress_bar = tqdm.tqdm(total=self.__EVOLVE_TIMES)
     self.__progress_bar.set_description('learning ' + str(self.__EVOLVE_TIMES) + ' times...')
     for times in range(1, self.__EVOLVE_TIMES + 1):
         game = game_board.GameBoard(first_agent,second_agent)
         game.game_start()
         if isinstance(first_agent, agent.DQNAgent):
             first_agent.weight_copy()
         if isinstance(second_agent, agent.DQNAgent):
             second_agent.weight_copy()
         if times % save_interval == 0:
             if isinstance(first_agent, agent.DQNAgent):
                 first_agent.save(file_path + str(times))
             if isinstance(second_agent, agent.DQNAgent):
                 second_agent.save(file_path + str(times) + "-rev")
         self.__progress_bar.update(1)
     self.__progress_bar.close()
Exemple #10
0
def battle_start_parallelization(times, first_agent, second_agent):
    progress_bar = tqdm.tqdm(total=times)
    executor = concurrent.futures.ProcessPoolExecutor()
    waiting_queue = []
    count = [0, 0, 0]
    for index in range(0, times):
        first_copy = first_agent.copy()
        second_copy = second_agent.copy()
        game = game_board.GameBoard(first_copy, second_copy)
        waiting_queue.append(executor.submit(game.game_start))
    for end_game in concurrent.futures.as_completed(waiting_queue):
        game_result = end_game.result()[0] + 1
        if game_result == 3:
            game_result = 1
        count[game_result] += 1
        progress_bar.update(1)
    progress_bar.close()
    output_match_result(times, count, first_agent, second_agent)
Exemple #11
0
 def __battle_random_agent(self, partner, is_first):
     waiting_queue = []
     for index in range(0, self.__NUMBER_INDIVIDUALS):
         for times in range(0, self.__NUMBER_INDIVIDUALS):
             if is_first:
                 first = self.__now_generation[index][0].copy()
                 second = partner.copy()
             else:
                 first = partner.copy()
                 second = self.__now_generation[index][0].copy()
             game = game_board.GameBoard(first, second)
             waiting_queue.append(self.__executor.submit(game.game_start, index))
     for end_task in concurrent.futures.as_completed(waiting_queue):
         self.__progress_bar.update(1)
         if end_task.result()[0] == -1 and is_first:
             self.__now_generation[end_task.result()[1]][1] += 1
         elif end_task.result()[0] == 1 and not is_first:
             self.__now_generation[end_task.result()[1]][1] += 1
Exemple #12
0
 def start(self, file_path, save_interval, first_agent, second_agent):
     if (not isinstance(first_agent, agent.Agent)) or (not isinstance(second_agent, agent.Agent)):
         raise Exception("The object of learning must be an Agent Class.")
     self.__progress_bar = tqdm.tqdm(total=self.__EVOLVE_TIMES)
     self.__progress_bar.set_description('learning ' + str(self.__EVOLVE_TIMES) + ' times...')
     for times in range(1, self.__EVOLVE_TIMES + 1):
         if isinstance(first_agent, agent.QLeaningAgent):
             first = first_agent
         else:
             first = first_agent.copy()
         if isinstance(second_agent, agent.QLeaningAgent):
             second = second_agent
         else:
             second = second_agent.copy()
         game = game_board.GameBoard(first, second)
         game.game_start()
         self.__learning_data.append([game.count_stones(-1), game.count_stones(1)])
         if times % save_interval == 0:
             if isinstance(first_agent, agent.QLeaningAgent):
                 first_agent.save_weight_vector(file_path + str(times))
             if isinstance(second_agent, agent.QLeaningAgent):
                 second_agent.save_weight_vector(file_path + str(times) + "-rev")
         self.__progress_bar.update(1)
     self.__progress_bar.close()
Exemple #13
0
        host = '127.0.0.1'
        port = 50001
    server = Server(host,port)
    # Size of the world ...
    print("Starting the Game Board")
    gameboard_file = './input_files/gameboard_file.txt'
    f = open(gameboard_file)
    l = f.readline().split(",")
    columns = int(l[0])
    rows = int(l[1])
    f.close()

    root = tk.Tk()

    images_directory = './images/'
    board = gb.GameBoard(root,columns,rows)
    board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
    # BOARD BOARD:
    # Read from files obstacles ...

    obstacles_file = './input_files//obstacles_file.txt'
    f = open(obstacles_file)
    obst_list = []
    for l in f.readlines():
        l = l.split(",")
        if len(l) > 1:
          obst_list.append( (int(l[0]),int(l[1])) )
    server.initialize_obstacles(images_directory,obst_list)
    #initialize_obstacles(images_directory,[(0,1),(4,6),(7,6),(6,7),(8,8)])
    f.close()
    # Defining the position of the 'goal' ...
Exemple #14
0
def run(ai=None, report=True):
    """
    Main function, runs one game of the chrome dino game

    :param ai: strategy to use
    :param report: If you want to see printed messages during run
    :return: Score of AI (num of seconds
    """

    # Allow time to refresh and user to enter into the game
    if report:
        print('Start in: ')
        for i in range(5, 0, -1):
            print(i)
            time.sleep(1)
    else:
        time.sleep(5)

    # Find the region of interest, and click there
    board = game_board.GameBoard()
    if board.found_roi:
        board.go_to_roi()
    else:
        print("Can't find game... exiting")
        return 0

    # allow some time for game to load and press space to start
    pyautogui.press('space')
    time.sleep(1)  # be easy - there's a starting animation

    game_on = True
    score = 0

    prior_obstacles = board.empty_obstacles
    last_stuck_check = time.time()

    # start game timer
    game_start = time.time()
    while game_on:

        # Take screen shot and find obstacles and score
        game_img = board.get_game_img()
        obstacles = board.find_obstacles(game_img)
        score = time.time() - game_start

        # Sometimes it takes too long to load and never starts in that case gets stuck.
        # Restart the function if it is long enough into the game, seeing an empty board and it happened last loop
        if time.time() - last_stuck_check > 10:
            last_stuck_check = time.time()

            if prior_obstacles == obstacles:
                print('game looks stuck! restarting!')
                return run(ai=ai, report=report)

            prior_obstacles = obstacles

        # Call game AI with game state - Uncomment AI you want to test/train
        if ai.jump(obstacles, score) >= .5:
            pyautogui.press('space')
            time.sleep(
                .5)  # so we don't mash the space bar and ruin everything

        # If game over, log score, and restart game
        if board.game_over(game_img):
            score = time.time() - game_start
            game_on = False
            if report:
                print('game over score: {0:0.1f}'.format(score))
            # restart
            pyautogui.hotkey('ctrl', 'r')

    return score
Exemple #15
0
def main():
    #Host and Port
    if len(sys.argv) == 3:
        host, port = sys.argv[1], int(sys.argv[2])
    else:
        host = '127.0.0.1'
        port = 50000
    # Size of the world ...
    print("Starting the Game Board")
    gameboard_file = 'input_files/gameboard_file.txt'
    f = open(gameboard_file)
    l = f.readline().split(",")
    columns = int(l[0])
    rows = int(l[1])
    f.close()
    root = tk.Tk()
    images_directory = 'images/'
    board = gb.GameBoard(root, columns, rows)
    board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
    #BOARD MAANAGER
    gm = GameManager(root, board, images_directory)
    # BOARD BOARD:
    #Read from files: initial agents position

    # Read from files: obstacles ...
    obstacles_file = 'input_files/obstacles_file.txt'
    f = open(obstacles_file)
    obst_list = []
    for l in f.readlines():
        l = l.split(",")
        if len(l) > 1:
            obst_list.append((int(l[0]), int(l[1])))

    gm.initialize_obstacles(images_directory, obst_list)
    #initialize_obstacles(images_directory,[(0,1),(4,6),(7,6),(6,7),(8,8)])
    f.close()
    # Defining the position of 'goals' ...
    goal_file = 'input_files/goal_file.txt'
    f = open(goal_file)
    goal_list = []
    for l in f.readlines():
        if len(l) > 1:
            l = l.split(",")
            goal_list.append((int(l[0]), int(l[1])))
        #print(goal_list)https://aihub.org/
    gm.initialize_goal(images_directory, goal_list)
    f.close()
    # Defining the bombs position:
    bomb_file = 'input_files/bomb_file.txt'
    f = open(bomb_file)
    bomb_list = []
    for l in f.readlines():
        if len(l) > 1:
            l = l.split(",")
            bomb_list.append((int(l[0]), int(l[1])))
        #print(bomb_list)
    gm.initialize_bomb(images_directory, bomb_list, rows, columns)
    f.close()
    # Initialize weights ...
    gm.initialize_weights(images_directory, rows, columns)
    root.update()
    # SERVER SERVER:
    # Starting server ...
    print("Starting the server!"),
    #server = s.Server()
    # Loop ...
    gm.loop(host, port)
 def setUp(self):
     self.board = game_board.GameBoard("../boards/test.brd")
Exemple #17
0
    dim = 10
    gametype = 0
    while not start_game:
        screen.fill(GOLD)
        graph.draw_menu(screen, dim, gametype)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                start_game, dim, gametype = graph.menu_click(
                    event.pos, dim, gametype)
        pygame.display.update()

    screen.fill(WHITE)
    board = game_board.GameBoard(dim, dim)
    graph.draw_grid(screen, board)
    pygame.display.update()

    gametype *= -1
    winner = 0
    player = 1
    move_coords = None
    while winner == 0:
        if gametype == player:
            move_coords = alphago.move(board.get_board(), player)
            move = board.move(move_coords, player)
            if move:
                player *= -1
            winner = board.check_winner()
            graph.draw_pieces(screen, board)
Exemple #18
0
    def __init__(self, dirname, hex_radius=20, caption="Hex Battle Simulator"):

        self.size = np.array(size)
        self.width, self.height = self.size
        #self.center = (0 + hex_radius, 0 + hex_radius)
        self.center = (self.size / 2).astype(np.int32)
        self.hex_radius = int(hex_radius *
                              scale)  # Radius of individual hexagons
        self.original_radius = self.hex_radius
        self.caption = caption
        self.board = hxgame.GameBoard(dirname)

        self.win_state = 0
        self.hex_map = hx.HexMap()

        temp_map_list = np.array([*self.board.values()])

        hexes = [
            VisualHex(coords.get_axial_coords(), COLORS[0], self.hex_radius)
            for coords in temp_map_list
        ]

        self.hex_map[np.array([c.get_axial_coords()
                               for c in temp_map_list])] = hexes

        self.movement_hex_image = make_hex_surface(
            (128, 128, 128, 255),  # Highlight color for a hexagon.
            self.hex_radius,  # radius of individual hexagon
            (255, 255, 255),  # Border color white
            hollow=True)

        self.attack_hex_image = make_hex_surface(
            (128, 128, 128, 255),  # Highlight color for a hexagon.
            self.hex_radius,  # radius of individual hexagon
            (255, 0, 0),  # Border color white
            hollow=True)

        self.moved_hex_image = make_hex_surface(
            (128, 128, 128, 255),  # Highlight color for a hexagon.
            self.hex_radius,  # radius of individual hexagon
            (128, 128, 128, 255))
        self.move_or_attack = 0

        self.clicked_hex = None
        self.axial_clicked = None
        self.valid_moves = None
        self.axial_moves = None
        self.temp_axial = None
        self.step = 1

        self.movement_counter = CyclicInteger(1, 1, 3)
        self.selected_movement_directions = []

        self.select_direction = CyclicInteger(0, 0, 5)
        self.turn_button = Button((0, 255, 0), int(750 * scale),
                                  int(20 * scale), int(225 * scale),
                                  int(75 * scale), 'End Turn')

        self.main_surf = None
        self.test_surf = None
        self.font = None
        self.fps_font = None
        self.clock = None
        self.init_pg()