Exemple #1
0
def UCT_play_game(n_iter=1000,
                  prune1=False,
                  zero_sum1=False,
                  epsilon1=0.,
                  prune2=False,
                  zero_sum2=False,
                  epsilon2=0.,
                  verbose=False):
    """ Play a sample game between two UCT players where each player gets a different number
        of UCT iterations (= simulations = tree nodes).
    """
    _verbose = verbose
    state1 = game_state.GameState(prune1, zero_sum1, epsilon1)
    state2 = game_state.GameState(prune2, zero_sum2, epsilon2)
    while ((state1.player_just_moved == 2 and len(state1.get_all_moves()) > 1
            and not (state1.py_pachi_board.is_terminal)) or
           (state2.player_just_moved == 1 and len(state2.get_all_moves()) > 1
            and not (state2.py_pachi_board.is_terminal))):
        if state1.player_just_moved == 1:
            m = UCT(rootstate=state2, itermax=n_iter, verbose=_verbose)
        else:
            m = UCT(rootstate=state1, itermax=n_iter, verbose=_verbose)
        print "Best Move: " + str(m) + "\n"
        state1.do_move(m)
        state2.do_move(m)
        if _verbose:
            print(state1.py_pachi_board)
    if state1.get_result(state1.player_just_moved) > 0:
        print "Player " + str(state1.player_just_moved) + " wins!"
    elif state1.get_result(state1.player_just_moved) < 0:
        print "Player " + str(3 - state1.player_just_moved) + " wins!"
    else:
        print "Nobody wins!"
Exemple #2
0
def main():

    os.environ["SDL_VIDEO_CENTERED"] = '1'  # center screen

    pygame.init()

    clock = pygame.time.Clock()

    screen = set_screen()
    ct.common_tiles.initiate_tiles()

    GS = game_state.GameState(screen, clock)

    clock_counter = dt.FPSClock(screen)

    while True:

        # update game state
        GS.update()

        # render game state
        GS.render_all()

        pygame.display.update()

        GS.clock.tick(FPS)
        clock_counter.show_time(GS.clock.get_fps())

        # get input
        GS.handle_input()
Exemple #3
0
    def __init__(self,
                 player_names,
                 randomize_play_order=True,
                 outfile="history.txt",
                 move_history_file=None):
        self.num_players = len(player_names)
        if not self.is_valid_num_players(self.num_players):
            print("Invalid number of players. Cannot create game instance...")
            raise ValueError("Invalid number of players")

        self.outfile = outfile
        self.move_history_file = move_history_file
        self.player_names = player_names

        if self.move_history_file is not None:
            with open(self.move_history_file, "r") as f:
                self.player_names = [
                    name.rstrip() for name in f.readline().split(" ")
                ]
        elif randomize_play_order:
            random.shuffle(self.player_names)

        self.game_state = gs.GameState(self.player_names)

        self.MAX_ACTION_ATTEMPTS = 10  # max num times we try to get an action
Exemple #4
0
 def __init__(self, xm, ym):
     self.game_xm = xm
     self.game_ym = ym
     cursor = (0, 0)
     grid = game_map.get_grid(xm, ym)
     cursor = grid.player_cells[0].position
     self.game_state = game_state.GameState(cursor, grid)
Exemple #5
0
    def test_game_state_localized(self):
        settings.change('language', 'Spanish')
        game_state_test = game_state.GameState(self.log)
        game_state_test.force_zero_map_time = True

        game_state_test.set_bulk(
            (False, 'ctf_mexico_b4', 'Engineer', '', 'Not queued', True))
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(
            str(game_state_test),
            'Engineer on ctf_mexico_b4, gamemode=ctf, hosting=True, queued="Not queued", server='
        )
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Mapa: ctf_mexico_b4 (alojamiento)',
                'state': 'El tiempo en el mapa: 0:00',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'ctf',
                    'large_text':
                    'Capturar la Bandera - TF2 Presencia Rica {tf2rpvnum}',
                    'small_image': 'engineer',
                    'small_text': 'Engineer'
                }
            })
        self.assertTrue(game_state_test.update_rpc)
Exemple #6
0
    def test_get_match_info(self):
        test_game_state = game_state.GameState(self.log)
        test_addresses = (
            '162.254.192.155:27053',  # valve
            'dal-1.us.uncletopia.com:27025',
            'chi.servers.creators.tf:27015',
            '192.223.26.238:27017',  # lazypurple
            '45.35.1.186:27065')  # blackwonder

        for test_address in test_addresses:
            try:
                server_data = test_game_state.get_match_data(
                    test_address, ['Server name', 'Player count', 'Kills'],
                    allow_network_errors=False)
                self.assertTrue(
                    server_data['player_count'].startswith("Players: "))
                self.assertIn(server_data['player_count'].split('/')[1],
                              ('24', '26', '30', '32'))
                self.assertEqual(server_data['kills'], "Kills: 0")

                if "Valve" in server_data['server_name']:
                    self.assertEqual(server_data['server_name'],
                                     "Valve Matchmaking Server (Virginia)")
            except Exception as error:
                raise AssertionError(f'{test_address}, {repr(error)}')

        settings.change('request_timeout', 0.001)
        self.assertEqual(
            test_game_state.get_match_data(
                test_addresses[-1], ['Server name', 'Player count', 'Kills']),
            server_data)
        self.assertEqual(test_game_state.get_match_data('', ['Player count']),
                         {'player_count': 'Players: ?/?'})
Exemple #7
0
 def test_square_graph(self):
     g = game_state.GameState()
     g.pathfinding_grid = graph_2d.SquareGraph(3, 3)
     path = g.pathfinding_grid.shortest_path((0, 0), (2, 2))
     self.assertEqual(path[0], (0, 0))
     self.assertEqual(path[-1], (2, 2))
     self.assertNotEqual(len(path), 2)
Exemple #8
0
 def test_move_character_impossible(self):
     g = game_state.GameState()
     g.pathfinding_grid = graph_2d.SquareGraph(3, 3)
     c = character.Character("Bob")
     g.characters[0] = c
     r = g.move_character(0, (2, 3))
     self.assertFalse(r.is_success)
Exemple #9
0
	def test_add_remove_auction_tiles(self):
		g_state = gs.GameState(["Test Player 1", "Test Player 2"])
		max_index = gi.NUM_AUCTIONABLE_TILE_TYPES - 1
		max_auction_tiles = g_state.get_max_auction_tiles()

		# test add and remove
		for _i in range(self.num_iterations):
			tiles_added = []

			# check that adding auction tiles works
			for _j in range(max_auction_tiles):
				rand_tile = random.randint(0, max_index - 1)
				tiles_added.append(rand_tile)
				g_state.add_tile_to_auction_tiles(rand_tile)
				self.assertEqual(tiles_added, g_state.get_auction_tiles())

			# check that adding too many auction tiles doesn't work
			try:
				rand_tile = random.randint(0, max_index - 1)
				g_state.add_tile_to_auction_tiles(rand_tile)
				self.assertTrue(False)
			except Exception:
				self.assertTrue(True)

			# check that removing auction tiles works
			for _j in range(len(tiles_added)):
				indx_to_remove = random.randint(0, len(tiles_added) - 1)
				tiles_added.pop(indx_to_remove)
				g_state.remove_auction_tile(indx_to_remove)

				self.assertEqual(tiles_added, g_state.get_auction_tiles())
Exemple #10
0
	def test_give_tiles_to_player(self):
		g_state = gs.GameState(["Test Player 1", "Test Player 2"])

		for _i in range(self.num_iterations):
			auction_tiles = []
			# add a random number of collectible tiles to a list
			num_auction_tiles = random.randint(1, g_state.get_max_auction_tiles() - 1)
			for _j in range(num_auction_tiles):
				t = g_state.draw_tile(log = False)
				if t is None:
					break
				if gi.index_is_collectible(t):
					auction_tiles.append(t)

			player_index = random.randint(0, 1)
			old_player_collection = g_state.get_player_collection(player_index)

			g_state.give_tiles_to_player(player_index, auction_tiles)

			new_player_collection = g_state.get_player_collection(player_index)

			# check that new player collection has 1 more of each auction tile
			for tile in auction_tiles:
				self.assertEqual(
					old_player_collection[tile] + auction_tiles.count(tile), 
					new_player_collection[tile]
				)
Exemple #11
0
    def __init__(self, player1, player2):
        board = Board()
        self._game_state = game_state.GameState(board, WHITE, None)

        self._players = {WHITE: player1, BLACK: player2}

        player1.side = WHITE
        player2.side = BLACK
Exemple #12
0
 def setup(self):
     print('setup_started')
     self.state = game_state.GameState()
     print('Game State created')
     self.state.create_new_game('F**k', 100)
     print('Game created')
     arcade.set_background_color(arcade.color.DARK_BROWN)
     print('setup_done')
 def initialise(self):
     """
     Initialise the state of the challenge
     """
     print("Establishing initial position...")
     self.state = gs.GameState()
     state_man = gsm.StateManager(self.conn, self.state)
     state_man.start()
     return state_man
Exemple #14
0
	def test_mark_player_passed(self):
		for _i in range(self.num_iterations):
			g_state = gs.GameState(["Test Player 1", "Test Player 2", "Test Player 3"])
			player_indexes = [0, 1, 2]
			random.shuffle(player_indexes)

			# mark players passed and make sure they are properly marked
			for index in player_indexes:
				g_state.mark_player_passed(index)
				self.assertTrue(not g_state.is_player_active(index))
Exemple #15
0
    def test_service_move_long(self):
        s = service.Service()
        s.state = game_state.GameState()
        s.state.pathfinding_grid = graph_2d.SquareGraph(3, 3)
        s.state.characters = {0: character.Character("Bob")}
        # character id, destination coordinate
        r = s.move(0, (2, 2))

        for _ in xrange(200):
            s.inc_tick()

        self.assertEqual(s.character_location(0), (2, 2))
Exemple #16
0
    def __init__(self, player_num, block_size, activate_gui, activate_terminal,
                 height, width):
        self.player_num = player_num
        self.height = height
        self.width = width

        self.activate_terminal = activate_terminal
        self.activate_gui = activate_gui
        self.block_size = block_size

        self.AIs = list()

        self.state = game_state.GameState(player_num, height, width)
Exemple #17
0
def test_board(all_result, states, max_time):
    counter = 1
    for state in states:
        print("running state: ", counter)
        counter += 1
        result = []
        result_expectimax = []
        result_monte_carlo = []
        i = 0
        while i < 50:
            print(i)
            start = time.time()
            ga = game_state.GameState(state[0], copy.deepcopy(state[1]),
                                      copy.deepcopy(state[2]), state[3],
                                      state[4], state[5],
                                      copy.deepcopy(state[6]))
            agent = multi_agents.ExpectimaxAgent(2)
            t = game.Game(agent)
            res = t.run(ga, max_time)
            end = time.time()
            i += 1
            result_expectimax.append([res[0], end - start, res[1]])
        result.append(result_expectimax)
        i = 0
        while i < 50:
            print(i)
            start = time.time()
            ga = game_state.GameState(state[0], copy.deepcopy(state[1]),
                                      copy.deepcopy(state[2]), state[3],
                                      state[4], state[5],
                                      copy.deepcopy(state[6]))
            agent = multi_agents.MonteCarloTreeSearchAgent(150)
            t = game.Game(agent)
            res = t.run(ga, max_time)
            end = time.time()
            i += 1
            result_monte_carlo.append([res[0], end - start, res[1]])
        result.append(result_monte_carlo)
        all_result.append(result)
Exemple #18
0
    def __init__(self, display_game=True):
        pygame.init()
        #self.font = pygame.font.Font(None, 60)
        self.playing = False
        self.display_game = display_game
        if self.display_game:
            self.screen = pygame.display.set_mode(SC.screen_size)

        player = Player(SC.player_start_pos, SC.initial_player_accel, 0)
        platforms = deque()
        hammers = deque()
        
        self.game_state = game_state.GameState(player, platforms, hammers, 0, False)
    def __init__(self):
        super(App, self).__init__()
        self._running = True
        self._display_surf = None
        self._image_surf = None
        self.background = None
        self.game_ui = None

        self.state_dict = None
        self.state_name = None
        self.state = None

        self.clock = pygame.time.Clock()
        self.current_game = game_state.GameState()
Exemple #20
0
	def test_drawing_all(self):
		g_state = gs.GameState(["Test Player 1", "Test Player 2"])

		# test that drawing all the tiles results in an empty tile bag
		starting_num_tiles = g_state.get_num_tiles_left()
		for _i in range(starting_num_tiles):
			_ = g_state.draw_tile()
		self.assertEqual(0, g_state.get_num_tiles_left())
		self.assertEqual(
			[0] * gi.NUM_TILE_TYPES, 
			g_state.get_tile_bag().get_bag_contents()
		)

		# test that trying to draw a tile after none are left returns none
		self.assertEqual(None, g_state.draw_tile(log = False))
Exemple #21
0
	def test_increase_round_number(self):
		g_state = gs.GameState(["Test Player 1", "Test Player 2"])
		max_rounds = g_state.get_total_rounds()
		starting_round = g_state.get_current_round()

		# check that increasing rounds works properly
		for i in range(max_rounds - starting_round):
			g_state.increase_round_number()
			self.assertEqual(g_state.get_current_round(), starting_round + i + 1)

		# check that increasing rounds when ur on the last round throws an error
		try:
			g_state.increase_round_number()
			self.assertTrue(False)
		except Exception:
			self.assertTrue(True)
Exemple #22
0
def send_response(data, ip):
    print('Calculating response...')
    json_d = json.loads(data)
    preview_map(json_d)
    print('-- GAME STATE --')
    #print(json.dumps(json_d, indent=2))
    gs = game_state.GameState(json_d)
    for p in gs.perceptions:
        #print('\t' + p.to_string(gs.unit_ids))
        if p.item_id == 1:
            game_state.GameState.wall[p.pos_y][p.pos_x] = 1
    print('--- END GAME ---')
    print('Sending response')
    ret = gs.handle_response(ip)
    print('-- CURRENT LOOP DONE --')
    return ret
Exemple #23
0
def new_game(args):
    first_player_args = args[0]
    second_player_args = args[1]

    first_agent, first_name = create_agent(first_player_args[0],
                                           first_player_args[1],
                                           first_player_args[2],
                                           first_player_args[3], 1)
    second_agent, second_name = create_agent(second_player_args[0],
                                             second_player_args[1],
                                             second_player_args[2],
                                             second_player_args[3], 2)

    initial_state = game_state.GameState(init=False)
    game = Game(first_agent, second_agent, first_name, second_name)

    return game.run(initial_state)
Exemple #24
0
	def test_reset_active_players(self):
		for _i in range(self.num_iterations):
			g_state = gs.GameState(["Test Player 1", "Test Player 2", "Test Player 3"])

			# mark some players passed
			player_indexes = [0, 1, 2]
			random.shuffle(player_indexes)
			player_indexes = player_indexes[:(random.randint(0, 3))]
			for index in player_indexes:
				g_state.mark_player_passed(index)

			# mark all players active
			g_state.reset_active_players()

			# make sure all players active
			for j in range(3):
				self.assertTrue(g_state.is_player_active(j))
Exemple #25
0
	def test_reset_num_ras_this_round(self):
		g_state = gs.GameState(["Test Player 1", "Test Player 2"])

		max_ras = g_state.get_num_ras_per_round()
		starting_num_ras = g_state.get_current_num_ras()

		# sanity check that game starts with 0 ras
		self.assertEqual(starting_num_ras, 0)

		# test that ras are reset properly
		for i in range(self.num_iterations):
			num_ras_to_add = random.randint(1, max_ras)
			for j in range(num_ras_to_add):
				g_state.increase_num_ras_this_round()
			self.assertEqual(num_ras_to_add, g_state.get_current_num_ras())
			g_state.reset_num_ras_this_round()
			self.assertEqual(0, g_state.get_current_num_ras())
Exemple #26
0
def play_game (inference):
    # Initialize memory
    actions = []
    policies = []
    indices = []
    moves = []

    # Set up search tree
    state = game_state.GameState()
    tree = mcts.MCTS(inference, state, num_threads=8)

    # Play game
    while not tree.state.done():
        print(tree.state.state.unicode())

        # Perform search
        node = tree.search(128)

        # Calculate move probabilities and get action index
        probs = mcts.policy(node, T=1.0)
        index = np.random.choice(len(node.actions), p=probs)

        # Get action and update tree
        action = node.actions[index]
        value = node.Q[index]
        move = tree.state.parse_action(action)

        print(tree.state.state.san(move), value)

        tree.act(index)

        # Store stats
        actions.append(action)
        policies.append(probs)
        indices.append(node.actions)
        moves.append(move)

    # Get game outcome and last player to move
    outcome = -tree.state.reward()
    winner = not tree.state.turn()

    print(tree.state.state.unicode())
    print(' '.join([chess.Board().variation_san(moves), state.state.result()]))

    return actions, policies, indices, outcome, winner
Exemple #27
0
    def get_action_sequence(self, tetris_game):
        """
        Given a Tetris object that represents the current state of the game, return a list of Event objects that
        represents a course of action.
        """

        self.expanded_nodes = 0
        best_score = -np.inf
        best_action_sequence = []
        tetris_game_state = game_state.GameState(tetris_game.field, tetris_game.figure.type)
        successors_dict = tetris_game_state.generate_agent_successors_dict()  # maps a game state to an event list.

        for successor in successors_dict.keys():
            value = self.expected_value(successor, 1)
            if value >= best_score:
                best_score = value
                best_action_sequence = successors_dict[successor]
        return best_action_sequence
Exemple #28
0
    def get_action_sequence(self, tetris_game):
        """
        Returns the minimax action
        """
        self.expanded_nodes = 0
        best_score = -np.inf
        alpha = -np.inf
        beta = np.inf
        best_action_sequence = []
        tetris_game_state = game_state.GameState(tetris_game.field, tetris_game.figure.type)
        successors_dict = tetris_game_state.generate_agent_successors_dict()  # maps a game state to an event list.

        for successor in successors_dict.keys():
            value = self.max_value(successor, 1, alpha, beta)
            if value >= best_score:
                best_score = value
                best_action_sequence = successors_dict[successor]
        return best_action_sequence
Exemple #29
0
def preview_map(json_data):
    gamestate = game_state.GameState(json_data)
    mat = np.zeros(
        (game_state.GameState.width, game_state.GameState.height, 3),
        dtype="uint8")
    cv2.bitwise_not(mat, mat, mask=game_state.GameState.wall)
    red_mat = np.full(
        (game_state.GameState.width, game_state.GameState.height, 3),
        (0, 0, 255),
        dtype="uint8")
    cv2.bitwise_or(red_mat, mat, mat, mask=game_state.GameState.movement)
    for p in gamestate.perceptions:
        color = (0, 0, 0)
        if p.item_id == 1:  # This is a wall
            color = (255, 255, 255)
        if p.item_id == 2:
            color = (255, 165, 0)
        if p.item_id == 2:
            color = (165, 42, 42)
        mat[p.pos_y, p.pos_x, :] = color
    for unit in gamestate.get_units():
        cv2.rectangle(mat, (unit.pos_x - game_state.GameState.range_num,
                            unit.pos_y - game_state.GameState.range_num),
                      (unit.pos_x + game_state.GameState.range_num,
                       unit.pos_y + game_state.GameState.range_num),
                      (0, 0, 255),
                      thickness=-1)
        cv2.drawMarker(mat, (unit.pos_x, unit.pos_y), (0, 255, 0),
                       markerType=cv2.MARKER_CROSS)
        cv2.putText(mat, str(unit.hp), (unit.pos_x, unit.pos_y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
        cv2.putText(mat, str(unit.ammo), (unit.pos_x, unit.pos_y - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
    for unit in gamestate.get_enemies():
        cv2.drawMarker(mat, (unit.pos_x, unit.pos_y), (255, 0, 0),
                       markerType=cv2.MARKER_CROSS)
    for unit in gamestate.get_ammos():
        cv2.drawMarker(mat, (unit.pos_x, unit.pos_y), (255, 255, 0),
                       markerType=cv2.MARKER_DIAMOND)
    for unit in gamestate.get_healths():
        cv2.drawMarker(mat, (unit.pos_x, unit.pos_y), (255, 0, 255),
                       markerType=cv2.MARKER_DIAMOND)
    cv2.imshow('[OE Kockanap] - Perception preview', mat)
    cv2.waitKey(1)
Exemple #30
0
	def test_clear_auction_tiles(self):
		g_state = gs.GameState(["Test Player 1", "Test Player 2"])
		max_index = gi.NUM_AUCTIONABLE_TILE_TYPES
		max_auction_tiles = g_state.get_max_auction_tiles()

		for _i in range(self.num_iterations):
			num_to_add = random.randint(0, max_auction_tiles)
			tiles_added = []

			# check that adding auction tiles works
			for _j in range(num_to_add):
				rand_tile = random.randint(0, max_index - 1)
				tiles_added.append(rand_tile)
				g_state.add_tile_to_auction_tiles(rand_tile)
				self.assertEqual(tiles_added, g_state.get_auction_tiles())

			# check that clearing auction tiles works
			g_state.clear_auction_tiles()
			self.assertEqual(g_state.get_auction_tiles(), [])