def __minimax_helper(game_state: GameState, maximizing_player, depth): if game_state.is_game_over: if game_state.winner.name == maximizing_player.name: return 100, None elif game_state.winner is SingletonDrawPlayer: return 0, None elif game_state.is_game_over: return -100, None scores = np.array([]) valid_moves = game_state.get_valid_moves() if game_state.current_player == maximizing_player: for move in valid_moves: new_game_state = game_state.copy().make_move(move) score = Minimax.__minimax_helper(new_game_state, maximizing_player, depth + 1) scores = np.append(scores, score[0]) max_eval = max(scores) arg_max_move = valid_moves[np.argmax(scores)] Minimax.__print_debugging_info(depth, scores, valid_moves, max_eval, arg_max_move) return max_eval, arg_max_move else: for move in valid_moves: new_game_state = game_state.copy().make_move(move) score = Minimax.__minimax_helper(new_game_state, maximizing_player, depth + 1) scores = np.append(scores, score[0]) return min(scores), None
def test_full_game(self): """ Test that I can run a game all the way to the end without an error.""" # Random, but fixed, opening hands. hand_0 = ['EA_', 'EO_', 'S10', 'G8_', 'S7_', 'SA_', 'GU_', 'E7_'] hand_1 = ['S8_', 'E10', 'SU_', 'GA_', 'HO_', 'H9_', 'H7_', 'SO_'] hand_2 = ['EU_', 'H8_', 'SK_', 'G7_', 'G9_', 'EK_', 'HU_', 'GO_'] hand_3 = ['HK_', 'HA_', 'GK_', 'H10', 'E9_', 'G10', 'E8_', 'S9_'] player_dict = {0: hand_0, 1: hand_1, 2: hand_2, 3: hand_3} # Player 1 calls a eichel partner play, (with player 0.) state = GameState(game_mode="Partner Eichel", offensive_player=1, active=0) for i in range(8): for j in range(4): hand = player_dict[state.active] possible = state.actions(hand) chosen = possible[0] # pick the first of the possible moves, don't want randomness in unittests. state = state.result(chosen) hand.remove(chosen) state.calculate_round_winner(state.history[-16:]) state.utilities() self.assertTrue(state.terminal_test()) self.assertEqual(state.played_the_ace(), 0) # correctly identifies who the partner is.
def __init__(self, manager): """manager is required to be a child of GameManager with these functions: -kill_player() -next_level() -add_score(amount) -give_energy(amount) -spend_energy(amount) -give_life() """ GameState.__init__(self, manager) self.player = Ship(*opt.player_args) self.enemy = EnemyBase(opt.mover_args, opt.spinner_args, opt.shooter_args, self.player) self.shield = EnemyShield(self.enemy, opt.shield_filename, formation, formation_center) self.hbullet = HomingBullet(opt.homer_filename, self.player, opt.homer_speed) self.cannon = Cannon(opt.deactivated_cannon_args, opt.standby_cannon_args, opt.firing_cannon_args, self.player) self.ion_field = IonField(*opt.ion_field_args) self.player_bullets = Group() self.reset_positions()
def __init__(self): ''' Constructor -- creates a new instance of Board Parameter: self -- The current Board object ''' self.state = GameState() turtle.setup(c.WIDTH + c.SQUARE_SIZE, c.HEIGHT + c.SQUARE_SIZE) turtle.screensize(c.WIDTH, c.HEIGHT) turtle.bgcolor("white") turtle.tracer(0, 0) # Create the Turtle to draw the board self.pen = turtle.Turtle() self.pen.penup() self.pen.hideturtle() # Draw the board and pieces self.draw_state() # "Convenience attributes" used for drawing self.high_bound = 0 - c.CORNER self.low_bound = c.CORNER self.screen = turtle.Screen() self.screen.onclick(self.clickhandler) turtle.done() # Stops the window from closing.
def test_unmortgage(self): state = GameState(1) player = state.players[0] # Set up player to own a mortgaged utility state.apply(GroupOfChanges([ GameStateChange.buy_property(state.squares[INDEX[ELECTRIC_COMPANY]], player, state.bank, mortgaged=True) ])) # Test unmortgage str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.unmortgage(state.squares[INDEX[ELECTRIC_COMPANY]], state) ])) str_after = str(state) expected_diff = [ # Player cash ('Cash: 1425', 'Cash: 1342'), # Bank cash ('Cash: 75', 'Cash: 158'), # Electric Company stats ('Mortgaged: True', 'Mortgaged: False') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Electric Company was not unmortgaged properly')
def test_change_position_landing_on_go(self): state = GameState(1) player = state.players[0] # Set up player's initial position at Short Line Railroad state.apply(GroupOfChanges([ GameStateChange.change_position(player, INDEX[SHORT_LINE_RAILROAD], state.bank, state.squares) ])) # Test player changing position to Go str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.change_position(player, INDEX[GO], state.bank, state.squares) ])) str_after = str(state) expected_diff = [ # Player stats ('Position: %d' % INDEX[SHORT_LINE_RAILROAD], 'Position: %d' % INDEX[GO]), ('Cash: 1500', 'Cash: 1700'), # Bank stats ('Cash: 0', 'Cash: -200') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Player did not pass Go properly')
def test_mortgage(self): state = GameState(1) player = state.players[0] # Set up player to own a railroad state.apply(GroupOfChanges([ GameStateChange.buy_property(state.squares[INDEX[PENNSYLVANIA_RAILROAD]], player, state.bank) ])) # Test mortgage str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.mortgage(state.squares[INDEX[PENNSYLVANIA_RAILROAD]], state) ])) str_after = str(state) expected_diff = [ # Player cash ('Cash: 1300', 'Cash: 1400'), # Bank cash ('Cash: 200', 'Cash: 100'), # Pennsylvania Railroad stats ('Mortgaged: False', 'Mortgaged: True') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Pennsylvania Railroad was not mortgaged properly')
def test_buy_property_from_something(self): state = GameState(1) player = state.players[0] # Set up player with some properties (two of the three greens) changes = [] for prop_name in [PACIFIC_AVENUE, PENNSYLVANIA_AVENUE]: changes.append(GameStateChange.buy_property(state.squares[INDEX[prop_name]], player, state.bank)) state.apply(GroupOfChanges(changes)) # Test buying North Carolina Avenue str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.buy_property(state.squares[INDEX[NORTH_CAROLINA_AVENUE]], player, state.bank) ])) str_after = str(state) expected_diff = [ # Player 1 stats ('Cash: 880', 'Cash: 580'), ('Pacific Avenue, Pennsylvania Avenue, ', 'Pacific Avenue, Pennsylvania Avenue, North Carolina Avenue, '), ('6: 2', '6: 3'), # Bank stats ('Cash: 620', 'Cash: 920'), ('Mediterranean Avenue, Baltic Avenue, Reading Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, St. Charles Place, Electric Company, States Avenue, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, North Carolina Avenue, Short Line Railroad, Park Place, Boardwalk, ', 'Mediterranean Avenue, Baltic Avenue, Reading Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, St. Charles Place, Electric Company, States Avenue, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, Short Line Railroad, Park Place, Boardwalk, '), ('6: 1', '6: 0') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='North Carolina Avenue was not purchased properly')
def test_buy_property_mortgaged(self): state = GameState(1) player = state.players[0] # Test buying Pennsylvania Avenue mortgaged str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.buy_property(state.squares[INDEX[PENNSYLVANIA_AVENUE]], player, state.bank, mortgaged=True) ])) str_after = str(state) expected_diff = [ # Player stats ('Cash: 1500', 'Cash: 1340'), ('', 'Pennsylvania Avenue, '), ('6: 0', '6: 1'), # Bank stats ('Cash: 0', 'Cash: 160'), ('Mediterranean Avenue, Baltic Avenue, Reading Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, St. Charles Place, Electric Company, States Avenue, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, Pacific Avenue, North Carolina Avenue, Pennsylvania Avenue, Short Line Railroad, Park Place, Boardwalk, ', 'Mediterranean Avenue, Baltic Avenue, Reading Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, St. Charles Place, Electric Company, States Avenue, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, Pacific Avenue, North Carolina Avenue, Short Line Railroad, Park Place, Boardwalk, '), ('6: 3', '6: 2'), # Pennsylvania Avenue stats ('Mortgaged: False', 'Mortgaged: True') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Pennsylvania Avenue was not mortgaged properly')
def check_partner(self): state = GameState(game_mode="Partner Eichel", offensive_player=0, active=0) fixed_history = [ "E7_", "E10", "EK_", "EA_", #player 0 starts, player 3 wins 25 pts "EO_", "HA_", "H10_", "HK_", # player 3 opens, player 3 wins 28 pts "SA_", "S10", "SK_", "S9_" ] # player 3 opens, player 3 wins 25 pts. for card in fixed_history: state = state.result(card) self.assertTrue(state.is_decided()) utilities = state.utilities(bools=False, intermediate=True) expected = (78, 0, 0, 78) self.assertEqual(expected, utilities)
def test_Copy(self): s = GameState() u = GameState() u.ball.pos_x = 100 u.ball.pos_y = 200 u.ball.vel_x = 300 u.ball.vel_y = 400 u.paddle_left.pos_y = -100 u.paddle_left.vel_y = -200 u.paddle_right.pos_y = -300 u.paddle_right.vel_y = -400 u.frame = 30 u.key_flags = 300 u.Copy(s) self.assertTrue(s.ball.pos_x == u.ball.pos_x) self.assertTrue(s.ball.pos_y == u.ball.pos_y) self.assertTrue(s.ball.vel_x == u.ball.vel_x) self.assertTrue(s.ball.vel_y == u.ball.vel_y) self.assertTrue(s.paddle_left.pos_y == u.paddle_left.pos_y) self.assertTrue(s.paddle_left.vel_y == u.paddle_left.vel_y) self.assertTrue(s.paddle_right.vel_y == u.paddle_right.vel_y) self.assertTrue(s.paddle_right.pos_y == u.paddle_right.pos_y) self.assertTrue(s.frame == u.frame) self.assertTrue(s.key_flags == u.key_flags) pass
def test_Serialize_and_Deserialize(self): s = GameState() s.ball.pos_x = 100 s.ball.pos_y = -50 s.ball.vel_x = -43 s.ball.vel_y = 6 s.paddle_left.pos_y = 90 s.paddle_left.vel_y = 4 s.paddle_right.pos_y = 2 s.paddle_right.vel_y = 87 s.key_flags = 3 s.frame = 112734590 s.keybits = 1 << 63 # Ignore the EventType header. b = s.Serialize()[4:] t = GameState() t.Deserialize(b) self.assertTrue(t.ball.pos_x == s.ball.pos_x) self.assertTrue(t.ball.pos_y == s.ball.pos_y) self.assertTrue(t.ball.vel_x == s.ball.vel_x) self.assertTrue(t.ball.vel_y == s.ball.vel_y) self.assertTrue(t.paddle_left.pos_y == s.paddle_left.pos_y) self.assertTrue(t.paddle_left.vel_y == s.paddle_left.vel_y) self.assertTrue(t.paddle_right.pos_y == s.paddle_right.pos_y) self.assertTrue(t.paddle_right.vel_y == s.paddle_right.vel_y) self.assertTrue(t.key_flags == s.key_flags) self.assertTrue(t.frame == s.frame) pass
def test_build_house(self): state = GameState(1) # Set up a player to own oranges with no houses player = state.players[0] oranges = [ST_JAMES_PLACE, TENNESSEE_AVENUE, NEW_YORK_AVENUE] changes = [] for prop_name in oranges: changes.append(GameStateChange.buy_property(state.squares[INDEX[prop_name]], player, state.bank)) state.apply(GroupOfChanges(changes)) # Test house build str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.build(state.squares[INDEX[NEW_YORK_AVENUE]], state) ])) str_after = str(state) expected_diff = [ ('Cash: 940', 'Cash: 840'), # player cash ('Cash: 560', 'Cash: 660'), # bank cash ('Num houses: 0', 'Num houses: 1'), # new york avenue ('Houses remaining: 32', 'Houses remaining: 31') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='House build was not applied properly')
class Agent(object): def __init__(self, name="Marty"): self.name = name self.gameState = None def ingestState(self, data): """ Ingests the given gamestate from the network. """ # ignorant agents might not do anything with the state if not data: return args = struct.unpack('!ffffffB',data) self.gameState = GameState(args[0],args[1],args[2],args[3],args[4],args[5]) self.gameState.parseFlags(args[6]) def chooseAction(self): """ Chooses an action, based off of a given game state. Returned is the bitwise or'ed set of actions. """ print "nothing" pass
def test_makes_suggested_move(self, mocked): """Should make move suggested by api.""" g = GameState() g.board = { 'a': {'1': 'R', '2': 'P', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': 'p', '8': 'r'}, # noqa 'b': {'1': 'N', '2': 'P', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': 'p', '8': 'n'}, # noqa 'c': {'1': 'B', '2': 'P', '3': ' ', '4': ' ', '5': 'p', '6': ' ', '7': ' ', '8': 'b'}, # noqa 'd': {'1': 'Q', '2': 'P', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': 'p', '8': 'q'}, # noqa 'e': {'1': 'K', '2': ' ', '3': ' ', '4': 'P', '5': ' ', '6': ' ', '7': 'p', '8': 'k'}, # noqa 'f': {'1': 'B', '2': 'P', '3': 'N', '4': ' ', '5': ' ', '6': ' ', '7': 'p', '8': 'b'}, # noqa 'g': {'1': ' ', '2': 'P', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': 'p', '8': 'n'}, # noqa 'h': {'1': 'R', '2': 'P', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': 'p', '8': 'r'}, # noqa } g.take_turn() expected = """ --------------------------------- 8 | r | n | b | q | k | b | n | r | |-------------------------------| 7 | p | p | | p | p | p | p | p | |-------------------------------| 6 | | | | | | | | | |-------------------------------| 5 | | | p | | | | | | |-------------------------------| 4 | P | | | | P | | | | |-------------------------------| 3 | | | | | | N | | | |-------------------------------| 2 | | P | P | P | | P | P | P | |-------------------------------| 1 | R | N | B | Q | K | B | | R | --------------------------------- a b c d e f g h """.strip('\n') # the outer newlines are only there to make this code readable self.assertEqual(g.board_text, expected)
def test_full_game(self): """ Test to see if during the course of a full game, we can correctly deduce which cards the other player has. I'm undecided as to whether we want this test to have a random element or not.""" # Random but fixed hands. hands = { 0: {'SK_', 'S7_', 'H10', 'H7_', 'HK_', 'E8_', 'HU_', 'GU_'}, 1: {'G9_', 'HO_', 'S10', 'H9_', 'EO_', 'E10', 'GO_', 'GK_'}, 2: {'G10', 'SU_', 'G8_', 'E9_', 'G7_', 'SO_', 'S9_', 'S8_'}, 3: {'GA_', 'EU_', 'E7_', 'H8_', 'SA_', 'EA_', 'EK_', 'HA_'} } state = GameState(game_mode="Herz Solo", offensive_player=1, active=0) for _ in range(32): active = state.active action = random.choice(state.actions(hands[active])) hands[active].remove(action) state = state.result(action) for i in range(4): card_constraints, _ = inverse_legal_moves(state, hands[i], i) for p_num, card_set in card_constraints.items(): actual_hand = hands[p_num] self.assertTrue(actual_hand.issubset(card_set))
def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Qiuyang's Tetris") pygame.key.set_repeat( 150, 40 ) # hold key will keep creating same event, set_repeat(delay, interval) # background color bg_color = BG_COLOR game_state = GameState(screen) while True: # if touch bottom if game_state.block and game_state.block.on_bottom: game_state.touch_bottom() # monitor keyboard and mouse event check_events(game_state) # fill background screen.fill(bg_color) # draw block if game_state.block: game_state.block.paint() # draw game window GameDisplay.draw_game_area(screen, game_state) # refresh the screen pygame.display.update()
def test_davonlaufen_2(self): """ Test if we can recognize if someone has run away, and enough cards of the called suit have been played such that we can conclude that the person who ran away has ALL of the remaining cards of the called suit. """ game_mode = "Partner Eichel" state = GameState(game_mode=game_mode, offensive_player=0, active=1) called_suit = "Eichel" suits_mapping = con.SUITS_MAPPING[game_mode] fixed_history = ["E7_", "EK_", "E10", "H8_"] hand = ["EO_", "GO_", "SO_", "HO_", "EU_", "GU_", "HU_"] for card in fixed_history: state = state.result(card) all_cards_except_eichel = { c for c in con.ALL_CARDS if suits_mapping[c] != called_suit } remaining_cards_except_eichel = { c for c in all_cards_except_eichel if not (c in hand or c in fixed_history) } expected = { 1: remaining_cards_except_eichel | {"EA_", "E8_", "E9_"}, 2: remaining_cards_except_eichel, 3: remaining_cards_except_eichel } card_constraints, number_constraints = inverse_legal_moves( state, hand, 0) self.assertEqual(expected, card_constraints)
def test_transfer_money_bank_to_player(self): import random state = GameState(1) player = state.players[0] # Transfer random amounts of money, and test that GameState is correct for trial in range(0, 100): player_cash_before = player.cash bank_cash_before = state.bank.cash amount = random.randint(1, player_cash_before) str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.transfer_money(state.bank, player, amount)])) str_after = str(state) expected_diff = [ # Player cash ('Cash: %d' % player_cash_before, 'Cash: %d' % (player_cash_before + amount)), # Bank cash ('Cash: %d' % bank_cash_before, 'Cash: %d' % (bank_cash_before - amount)) ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='$%d was not transferred to player correctly. Here is diff:' % amount)
def main() -> None: game_state: GameState = GameState.initial() print(display_board(game_state.board)) # ユーザアクションを取得 input_action: str = input() # "quit"入力で修了 while input_action != "quit": # 盤面記法が書かれたらゲームの状態を指定通りにリセット if Board.is_valid_notation(input_action): # 入力アクションを元にゲーム状態を生成 board = Board.from_notation(input_action) game_state = GameState(board) # コンソールに盤面出力 print(display_board(game_state.board)) # 棋譜記法が書かれたらゲームの状態に適用 elif FillAction.is_valid_notation(input_action): action: FillAction = FillAction.from_notation(input_action) game_state: GameState = action.apply_to(game_state) # コンソールに盤面出力 print(display_board(game_state.board)) else: print("正しい値を入力してください") input_action = input()
def build_table(num_rounds=NUM_ROUNDS): """Build a basic opening book of moves.""" import random initial_moves = [ (2, 2), (1, 1), (0, 0), (0, 2), (2, 0), (1, 2), (2, 1), (3, 3), (3, 1), (1, 3), ] openingbook = {} for i, move in enumerate(initial_moves): game = GameState() liberties = game.liberties(game._player_locations[game.player()]) if move not in liberties: move = random.choice(liberties) game = game.result(move) openingbook[game.hashable] = move return openingbook
def test_demolish_house(self): state = GameState(1) # Set up a player to own a property with 1 house player = state.players[0] park_place = state.squares[INDEX[PARK_PLACE]] boardwalk = state.squares[INDEX[BOARDWALK]] state.apply( GroupOfChanges( [GameStateChange.buy_property(park_place, player, state.bank)])) state.apply( GroupOfChanges( [GameStateChange.buy_property(boardwalk, player, state.bank)])) state.apply(GroupOfChanges([GameStateChange.build(boardwalk, state)])) # Test applying the changes by comparing differences in their string # encodings. Ensure that no additional changes were made to the state. str_before = str(state) state.apply( GroupOfChanges([GameStateChange.demolish(boardwalk, state)])) str_after = str(state) expected_diff = [ ('Cash: 550', 'Cash: 650'), # player cash ('Cash: 950', 'Cash: 850'), # bank cash ('Num houses: 1', 'Num houses: 0'), ('Houses remaining: 31', 'Houses remaining: 32') ] self.assertDiffGameStates( str_before, str_after, expected_diff, msg='House demolition was not applied correctly')
def test_init(self): """Tests the initialization of a GameState""" GameStateTest.G.add_edge(0, 1) state = GameState(GameStateTest.G) self.assertEquals(state.turn, labels.RED) self.assertFalse(state.is_gameover()) self.assertFalse(state.is_terminal())
def test_buy_property_from_nothing(self): state = GameState(1) player = state.players[0] # Test buying Pacific Avenue str_before = str(state) state.apply( GroupOfChanges([ GameStateChange.buy_property( state.squares[INDEX[PACIFIC_AVENUE]], player, state.bank) ])) str_after = str(state) expected_diff = [ # Player 1 stats ('Cash: 1500', 'Cash: 1200'), ('', 'Pacific Avenue, '), ('6: 0', '6: 1'), # Bank stats ('Cash: 0', 'Cash: 300'), ('Mediterranean Avenue, Baltic Avenue, Reading Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, St. Charles Place, Electric Company, States Avenue, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, Pacific Avenue, North Carolina Avenue, Pennsylvania Avenue, Short Line Railroad, Park Place, Boardwalk, ', 'Mediterranean Avenue, Baltic Avenue, Reading Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, St. Charles Place, Electric Company, States Avenue, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, North Carolina Avenue, Pennsylvania Avenue, Short Line Railroad, Park Place, Boardwalk, ' ), ('6: 3', '6: 2') ] self.assertDiffGameStates( str_before, str_after, expected_diff, msg='Pacific Avenue was not purchased properly')
def run(): 'parse input, update game state and call the bot classes do_turn method' gamestate = GameState() bot = MyBot(gamestate) map_data = '' while(True): try: current_line = sys.stdin.readline().rstrip('\r\n') # string new line char if current_line.lower() == 'ready': gamestate.setup(map_data) bot.do_setup() gamestate.finish_turn() map_data = '' elif current_line.lower() == 'go': gamestate.update(map_data) # call the do_turn method of the class passed in bot.do_turn() gamestate.finish_turn() map_data = '' else: map_data += current_line + '\n' except EOFError: break except KeyboardInterrupt: raise except: # don't raise error or return so that bot attempts to stay alive traceback.print_exc(file=sys.stderr) sys.stderr.flush()
def backup(self, node, turn, outcome, state: GameState): """ Update the node statistics on the path from the passed node to root to reflect the outcome of a randomly simulated playout. """ # Careful: The reward is calculated for player who just played # at the node and not the next player to play pl_length = [state.get_num_played()['white'], state.get_num_played()['black']] self.pl_list = append(self.pl_list, [pl_length], axis=0) bonus = self.modify_reward(pl_length) reward = -1 if outcome == turn else 1 while node is not None: node.N += 1 max_moves_played = max(state.get_num_played().values()) if turn == GameMeta.PLAYERS['black']: qb_reward = reward + (reward * MCTSMeta.A_CONST * bonus['black']) \ if max_moves_played >= MCTSMeta.WARMUP_ROLLOUTS else reward else: qb_reward = reward + (reward * MCTSMeta.A_CONST * bonus['white']) \ if max_moves_played >= MCTSMeta.WARMUP_ROLLOUTS else reward node.Q += qb_reward turn = 1 if turn == 0 else 0 node = node.parent reward = -reward
def test_invalid_move(self): """Tests that invalid moves raise an exception""" GameStateTest.G.add_edge(0, 1) state = GameState(GameStateTest.G) state.make_move(0) state.make_move(1) self.assertRaises(InvalidMoveException)
def receive_once(self): """ Receives a package and interprets it. Calls :func:`on_new_gamestate` Sends an answer to the GC """ try: data, peer = self.socket.recvfrom(GameState.sizeof()) print(len(data)) # Throws a ConstError if it doesn't work parsed_state = GameState.parse(data) # Assign the new package after it parsed successful to the state self.state = parsed_state self.time = time.time() # Call the handler for the package self.on_new_gamestate(self.state) # Answer the GameController self.answer_to_gamecontroller(peer) except AssertionError as ae: logger.error(ae.message) except socket.timeout: logger.warning("Socket timeout") except ConstError: logger.warning("Parse Error: Probably using an old protocol!") except Exception as e: logger.exception(e) pass
def test_is_on_board(self): game = GameState() self.assertTrue(game.is_on_board(0, 0)) self.assertTrue(game.is_on_board(4, 5)) self.assertFalse(game.is_on_board(-1, 0)) self.assertFalse(game.is_on_board(8, 0)) self.assertFalse(game.is_on_board(0, 8))
def main(): #初始化pygame。启用Pygame必不可少的一步,在程序开始阶段执行。 pygame.init() #创建屏幕对象 screen = pygame.display.set_mode((1200, 900)) #分辨率是1200*900 pygame.display.set_caption("俄罗斯方块") #窗口标题 pygame.key.set_repeat(100, 100) # 一直按下某个键,每过100毫秒就引发一个KEYDOWN事件 #屏幕背景色 bg_color = (230, 230, 230) game_state = GameState(screen) game_resource = GameResource() game_resource.play_bg_music() #游戏主循环 while True: #方块触底的话 if game_state.piece and game_state.piece.is_on_bottom: game_state.touch_bottom() #监视键盘和鼠标事件 check_events(game_state, game_resource) #设定屏幕背景 screen.blit(game_resource.load_bg_img(), (0, 0)) #绘制方块 if game_state.piece: game_state.piece.paint() #绘制游戏区域网格线和墙体 GameDisplay.draw_game_window(screen, game_state, game_resource) #让最近绘制的屏幕可见 pygame.display.flip()
def test_transfer_money_bank_to_player(self): import random state = GameState(1) player = state.players[0] # Transfer random amounts of money, and test that GameState is correct for trial in range(0, 100): player_cash_before = player.cash bank_cash_before = state.bank.cash amount = random.randint(1, player_cash_before) str_before = str(state) state.apply( GroupOfChanges([ GameStateChange.transfer_money(state.bank, player, amount) ])) str_after = str(state) expected_diff = [ # Player cash ('Cash: %d' % player_cash_before, 'Cash: %d' % (player_cash_before + amount)), # Bank cash ('Cash: %d' % bank_cash_before, 'Cash: %d' % (bank_cash_before - amount)) ] self.assertDiffGameStates( str_before, str_after, expected_diff, msg='$%d was not transferred to player correctly. Here is diff:' % amount)
def __init__(self, player): self.digraph = nx.DiGraph() self.player = player self.num_simulations = 0 # Constant parameter to weight exploration vs. exploitation for UCT self.uct_c = np.sqrt(2) self.node_counter = 0 empty_board = GameState() self.digraph.add_node(self.node_counter, attr_dict={'w': 0, 'n': 0, 'uct': 0, 'expanded': False, 'state': empty_board}) empty_board_node_id = self.node_counter self.node_counter += 1 self.last_move = None if player is 'O': for successor in [empty_board.transition_function(*move) for move in empty_board.legal_moves()]: self.digraph.add_node(self.node_counter, attr_dict={'w': 0, 'n': 0, 'uct': 0, 'expanded': False, 'state': successor}) self.digraph.add_edge(empty_board_node_id, self.node_counter) self.node_counter += 1
def run_mcts_simulation(max_num_dice=5, player1_name="MctsBot", player2_name="player2", num_rounds=10000): """ Set up and simulate many rounds using Monte Carlo Tree Search (mcts). Args: max_num_dice (int): the number of dice each player starts with. player1_name (string): name for player1 player2_name (string): name for player2 """ player2bot = int(input("Please enter player 2 type: 1 for human, 2 for random, 3 for nextNum, 4 for nextFace, 5 for challenge, 6 for probability, 7 for savedQBot: ")) player2 = None if player2bot == 1: player2 = Player(max_num_dice, player2_name) elif player2bot == 2: player2_name = "Random Bot" player2 = Random_Bot(max_num_dice, player2_name) elif player2bot == 3: player2_name = "Next Number Bot" player2 = Bot_NextNum(max_num_dice, player2_name) elif player2bot == 4: player2_name = "Next Face Bot" player2 = Bot_NextFace(max_num_dice, player2_name) elif player2bot == 5: player2_name = "Challenge Bot" player2 = Bot_Challenge(max_num_dice, player2_name) elif player2bot == 6: player2_name = "Probability Bot" player2 = ProbabilityBot(max_num_dice, player2_name) elif player2bot == 7: player2_name = "Saved Q Bot" player2 = SavedQBot(max_num_dice, player2_name) mctsbot = MctsBot(max_num_dice, player1_name) game = GameState(mctsbot, player2) wins = { player1_name : 0, player2_name: 0 } for i in range(num_rounds): winner = simulate_mcts_round(game) wins[winner.name] += 1 plot_color = "" if winner.name == player1_name: plot_color = "blue" else: plot_color = "red" plt.scatter(i, wins[winner.name] / (i + 1), color=plot_color) game.reset_to_round_start() print("RESULTS") print("Wins for {}: {}\n".format(player1_name, wins[player1_name])) print("Wins for {}: {}\n".format(player2_name, wins[player2_name])) plt.title("Percentage of Wins Over Time") plt.xlabel("Rounds") plt.ylabel("Percentage of Wins") player1_legend = mpatches.Patch(color="blue", label=player1_name) player2_legend = mpatches.Patch(color="red", label=player2_name) plt.legend(handles=[player1_legend, player2_legend]) plt.show()
def test_invalid_fen_string(self): """ If fen string is not valid fen, should raise InvalidFENFileError. """ g = GameState() with self.assertRaises(InvalidFENFileError): g._parse_fen_str('asdf 32ds 0-=fe')
def __init__(self, manager, score, lives, next_state): GameState.__init__(self, manager) sys_font = Font(get_default_font(), options.font_size) self.score_text = sys_font.render(str(score), True, options.white) self.lives_text = sys_font.render(str(lives), True, options.white) self.next_state = next_state
def main(fen_file): game_state = GameState(fen_file) game_state.take_turn() print() print(game_state.board_text) print() print(game_state.fen) print()
def test_get_piece_moves(self): game = GameState() move1 = game.get_piece_moves(Piece(c.PLAYER1, 2, 1)) move2 = game.get_piece_moves(Piece(c.PLAYER2, 4, 5)) move3 = game.get_piece_moves(Piece(c.PLAYER1, 0, 1)) self.assertEqual(move1.sort(), [[1, -1], [1, 1]].sort()) self.assertEqual(move2.sort(), [[-1, -1], [-1, 1]].sort()) self.assertEqual(move3, [])
def __init__(self, manager): GameState.__init__(self, manager) sys_font = Font(get_default_font(), options.font_size) self.message1 = sys_font.render("Andrew's Bitchin' Yars' Revenge Clone", True, options.white) self.message2 = sys_font.render("Press shoot button (space) to start.", True, options.white)
def test_en_passant_non_pawn_moves_two_squares(self): """ Even if a non-pawn moves two spaces, en passant should be None. """ game = GameState() game.board['a']['1'] = 'R' game._make_move('a1a3') self.assertEqual(game.en_passant, None)
def __init__(self, player): """ Implementation of Monte Carlo Tree Search Creates a root of an MCTS tree to keep track of the information obtained throughout the course of the game in the form of a tree of MCTS nodes The data structure of a node consists of: - the game state which it corresponds to - w, the number of wins that have occurred at or below it in the tree - n, the number of plays that have occurred at or below it in the tree - expanded, whether all the children (legal moves) of the node have been added to the tree To access the node attributes, use the following format. For example, to access the attribute 'n' of the root node: policy = MCTSPolicy() current_node = policy.root policy.tree.node[current_node]['n'] """ self.digraph = nx.DiGraph() self.player = player self.num_simulations = 0 # Constant parameter to weight exploration vs. exploitation for UCT self.uct_c = np.sqrt(2) self.node_counter = 0 empty_board = GameState() self.digraph.add_node(self.node_counter, attr_dict={ 'w': 0, 'n': 0, 'uct': 0, 'expanded': False, 'state': empty_board }) empty_board_node_id = self.node_counter self.node_counter += 1 self.last_move = None if player is 'O': for successor in [ empty_board.transition_function(*move) for move in empty_board.legal_moves() ]: self.digraph.add_node(self.node_counter, attr_dict={ 'w': 0, 'n': 0, 'uct': 0, 'expanded': False, 'state': successor }) self.digraph.add_edge(empty_board_node_id, self.node_counter) self.node_counter += 1
def run(self): self.game_state = GameState(self.conf_obj["initial_moves"], self.conf_obj["initial_drills"], self.conf_obj['layout']) # reset self.game_state.update_players_points() cycle = -1 # play: set cycle = -1 update_phase_timer = 0 phase_interval = self.conf_obj["time_per_display_phase"] clock = self.clock playtime = 0 while self.running: miliseconds = clock.tick(self.FPS) playtime += miliseconds / 1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False text = "FPS: {0:2f} Playtime: {1:2f}".format(clock.get_fps(), playtime) pygame.display.set_caption(text) # update by timer update_phase_timer += miliseconds/1000 if self.turn < self.end_turn and update_phase_timer > phase_interval: update_phase_timer = 0 cycle += 1 cycle %= 5 if cycle == 0: # simulate write input, run program, get output, ... # actually just read log file gen from self.run_player_program() for plr_idx in range(2): copyfile('{}/{:03d}_output{}.log'.format(self.LOG_PATH, self.turn, plr_idx), \ '{}/player{}/{}.OUT'.format(self.DATA_PATH, plr_idx, self.EXEC_NAME)) self.output_actions[plr_idx] = self.pim.read_output(self.game_state, plr_idx) self.turn += 1 elif cycle == 1: # display intention self.game_state.update_intentions(self.output_actions[0], self.output_actions[1]) elif cycle == 2: # display actions self.game_state.update_actions() self.game_state.update_players_points() self.game_state.intentions = [None, None] elif cycle == 3: # update_zones self.game_state.board.update_zones() self.game_state.update_players_points() elif cycle == 4: # remove full zones self.game_state.board.remove_full_zones() self.draw() pygame.display.flip()
def test_PlayFrame(self): '''Test frame count and key_flags in PlayFrame. ''' e = UDPGameEngine() s = GameState() frame = s.frame s.key_flags = GameEvent.EVENT_FLAP_LEFT_PADDLE e.PlayFrame(s, s.key_flags, e.bitrec) self.assertTrue(s.frame == frame + 1)
def setUp(self): self.bot = MonteCarloBot() self.bot.hand = [ 'G7_', 'HO_', 'EO_', 'GU_', 'HU_', 'SA_', 'GK_', 'EK_' ] game_mode = "Herz Solo" self.state = GameState(game_mode=game_mode, offensive_player=0, active=0)
def test_RotateRoles_1(self): e = UDPGameEngine() s = GameState() s.player_size = 1 s.roles = [GameState.ROLE_LEFT_PADDLE] s.players = [-1, 0] e.RotateRoles(s) self.assertTrue(s.roles == [GameState.ROLE_LEFT_PADDLE]) self.assertTrue(s.players == [-1, 0])
def test_draw_card(self): state = GameState(1) player = state.players[0] # Test every card in both decks dict_card_types = { CHANCE_CARD: 'Chance', COMMUNITY_CHEST_CARD: 'Community Chest' } for card_type, card_str in dict_card_types.iteritems(): deck = state.decks[card_type] # Draw every card in the deck, check that cards are handled correctly # and that nothing else in the state is changed card = None for i in range(0, deck.size()): card = deck.peek() jail_free_count_before = player.jail_free_count str_before = str(state) expected_diff = None # initialized in the following if-block state.apply( GroupOfChanges([GameStateChange.draw_card(deck, player)])) if card == LMBDA_GET_OUT_OF_JAIL_FREE: # Check that the card is not replaced on the deck, and that the # player's Jail Free card count is incremented. self.assertEqual(player.jail_free_count, jail_free_count_before + 1) for j in range(0, deck.size()): self.assertNotEqual(deck.draw(), LMBDA_GET_OUT_OF_JAIL_FREE) # Initialize. Used after this if-block to ensure that nothing else # in the state was changed. expected_diff = [ ('Jail free count: %d' % jail_free_count_before, 'Jail free count: %d' % player.jail_free_count) ] else: # Check that the card is replaced on the bottom if it is not the # Jail Free card. for j in range(0, deck.size() - 1): deck.draw() self.assertEqual(deck.draw(), card) # compare with last card # Initialize expected_diff = [] # Check that the rest of the state is unchanged by comparing the # string encodings of the GameStates str_after = str(state) self.assertDiffGameStates( str_before, str_after, expected_diff, msg='The GameState was not modified correctly')
def __init__(self, gsm, view): """Initialisation des ressources et des modèles (une seule fois)""" GameState.__init__(self, gsm, view) self.areas = {} self.area = None self.description_hash = {} self.default_verb = 'look_at' self._action_subject = models.ActionSubject(self, self.default_verb) self._complement = None # idem self.inventory = models.Inventory(self)
def test_demolish_house(self): state = GameState(1) # Set up a player to own a property with 1 house player = state.players[0] park_place = state.squares[INDEX[PARK_PLACE]] boardwalk = state.squares[INDEX[BOARDWALK]] state.apply(GroupOfChanges([ GameStateChange.buy_property(park_place, player, state.bank)])) state.apply(GroupOfChanges([ GameStateChange.buy_property(boardwalk, player, state.bank)])) state.apply(GroupOfChanges([ GameStateChange.build(boardwalk, state)])) # Test applying the changes by comparing differences in their string # encodings. Ensure that no additional changes were made to the state. str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.demolish(boardwalk, state)])) str_after = str(state) expected_diff = [ ('Cash: 550', 'Cash: 650'), # player cash ('Cash: 950', 'Cash: 850'), # bank cash ('Num houses: 1', 'Num houses: 0'), ('Houses remaining: 31', 'Houses remaining: 32') ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='House demolition was not applied correctly')
def handle_input(log, END_GAME = False): """ Handles all external input,such as those keyboard and mouse. """ for event in pygame.event.get(): keys = pygame.key.get_pressed() # Closing handle_quit(event) if keyboard.queue_prompt(event): game_state.next_wave() # Pausing game if keyboard.pause_prompt(keys): game_state.toggle_paused() # Hero's movement hero_dir = keyboard.movement(keys) game_state.hero.change_direction(hero_dir) #END_GAME global game_state handle_quit(event, END_GAME) if keyboard.restart(event, END_GAME): if game_state.mode == "FIXED": new_choice = "DYNAMIC" else: new_choice = "FIXED" game_state = GameState(new_choice) log.refresh(new_choice) log.first_row() # Sound Adjustment if keyboard.music_prompt(keys): dj.switch_background_music() if keyboard.increase_prompt(keys): dj.increase_volume() if keyboard.decrease_prompt(keys): dj.decrease_volume() # Shoot Laser if keyboard.laser_prompt(keys): if game_state.hero.laser_equipped: game_state.hero.is_firing_laser = True game_state.hero.fire_time = time.clock() # Shoot Pew if keyboard.pew_prompt(keys): if game_state.hero.ok_to_shoot(): game_state.hero_fire() dj.play_pew()
def __init__(self, parent): GameState.__init__(self, parent) # White background self.g_background = GLSpriteGroup() background = ColorBackground(0.0, 0.0, 800.0, 600.0, (255, 255, 255)) self.g_background.add(background) self.timer = 1500 self.menu_added = False self.background_alpha = 1.0
def test_ReadAndWriteEvent_State_2(self): evt = GameState() evt.frame = 100 evt.ball.pos_x = 3 evt.ball.pos_y = 6 evt.paddle_left.pos_y = 5 evt.paddle_left.vel_y = -9 evt.paddle_right.pos_y = -19 evt.paddle_right.vel_y = 54 evt.key_flags = 4 self.template_ReadAndWriteEvent(evt)
def test_eliminate_to_player(self): state = GameState(2) player_eliminated = state.players[0] player_eliminator = state.players[1] # Set up players to have some clout self.setup_eliminated_player(state) self.setup_eliminator_player(state) # Move player_eliminated to a square where he would likely lose to the # other player (e.g. Marvin Gardens) state.apply(GroupOfChanges([ GameStateChange.change_position(player_eliminated, INDEX[MARVIN_GARDENS], state.bank, state.squares) ])) # Eliminate player_eliminated to player_eliminator, and test that # player_eliminated's belongings are properly transferred to the # player_eliminator and that no other changes are made to the state. str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.eliminate(player_eliminated, player_eliminator, state)])) str_after = str(state) expected_diff = [ # Eliminated player stats ('Position: %d' % INDEX[MARVIN_GARDENS], 'Position: -1'), ('Cash: 560', 'Cash: 0'), ('Oriental Avenue, Vermont Avenue, Connecticut Avenue, States Avenue, Short Line Railroad, ', ''), ('1: 3', '1: 0'), ('2: 1', '2: 0'), ('100: 1', '100: 0'), ('Jail free count: 1', 'Jail free count: 0'), ('Is in game: True', 'Is in game: False'), # Eliminator player stats ('Cash: 250', 'Cash: 1035'), ('Atlantic Avenue, Ventnor Avenue, Marvin Gardens, Reading Railroad, Pennsylvania Railroad, B. & O. Railroad, ', 'Atlantic Avenue, Ventnor Avenue, Marvin Gardens, Reading Railroad, Pennsylvania Railroad, B. & O. Railroad, Oriental Avenue, Vermont Avenue, Connecticut Avenue, States Avenue, Short Line Railroad, '), ('1: 0', '1: 3'), ('2: 0', '2: 1'), ('100: 3', '100: 4'), ('Jail free count: 0', 'Jail free count: 1'), # Property stats ('Num houses: 3', 'Num houses: 0'), # Oriental Avenue ('Num houses: 3', 'Num houses: 0'), # Vermont Avenue ('Num houses: 3', 'Num houses: 0'), # Connecticut Avenue # Housing stats ('Houses remaining: 14', 'Houses remaining: 23') # 9 houses from light blues ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Player was not eliminated properly. The following changes were made to the GameState:')
def test_RotateRoles_2(self): e = UDPGameEngine() s = GameState() s.player_size = 2 s.roles = [GameState.ROLE_LEFT_PADDLE, GameState.ROLE_RIGHT_PADDLE] s.players = [-1]*(s.player_size + 1) s.players[GameState.ROLE_LEFT_PADDLE] = 0 s.players[GameState.ROLE_RIGHT_PADDLE] = 1 e.RotateRoles(s) self.assertTrue(s.roles == [GameState.ROLE_RIGHT_PADDLE, GameState.ROLE_LEFT_PADDLE]) self.assertTrue(s.players == [-1, 1, 0])
def test_eliminate_to_bank(self): state = GameState(1) player = state.players[0] # Set up player to have some clout self.setup_eliminated_player(state) # Move player to a square where he would likely lose to the bank (e.g. # Luxury Tax) state.apply(GroupOfChanges([ GameStateChange.change_position(player, INDEX[LUXURY_TAX], state.bank, state.squares) ])) # Eliminate the player to the bank, and test that the player's belongings # are properly transferred to the bank and that no other changes are # made to the state. str_before = str(state) state.apply(GroupOfChanges([ GameStateChange.eliminate(player, state.bank, state)])) str_after = str(state) expected_diff = [ # Player stats ('Position: %d' % INDEX[LUXURY_TAX], 'Position: -1'), ('Cash: 560', 'Cash: 0'), ('Oriental Avenue, Vermont Avenue, Connecticut Avenue, States Avenue, Short Line Railroad, ', ''), ('1: 3', '1: 0'), ('2: 1', '2: 0'), ('100: 1', '100: 0'), ('Jail free count: 1', 'Jail free count: 0'), ('Is in game: True', 'Is in game: False'), # Bank stats ('Cash: 940', 'Cash: 1725'), ('Mediterranean Avenue, Baltic Avenue, Reading Railroad, St. Charles Place, Electric Company, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, Pacific Avenue, North Carolina Avenue, Pennsylvania Avenue, Park Place, Boardwalk, ', 'Mediterranean Avenue, Baltic Avenue, Reading Railroad, St. Charles Place, Electric Company, Virginia Avenue, Pennsylvania Railroad, St. James Place, Tennessee Avenue, New York Avenue, Kentucky Avenue, Indiana Avenue, Illinois Avenue, B. & O. Railroad, Atlantic Avenue, Ventnor Avenue, Water Works, Marvin Gardens, Pacific Avenue, North Carolina Avenue, Pennsylvania Avenue, Park Place, Boardwalk, Oriental Avenue, Vermont Avenue, Connecticut Avenue, States Avenue, Short Line Railroad, '), ('1: 0', '1: 3'), ('2: 2', '2: 3'), ('100: 3', '100: 4'), # Property stats ('Num houses: 3', 'Num houses: 0'), # Oriental Avenue ('Num houses: 3', 'Num houses: 0'), # Vermont Avenue ('Num houses: 3', 'Num houses: 0'), # Connecticut Avenue ('Mortgaged: True', 'Mortgaged: False'), # States Avenue ('Mortgaged: True', 'Mortgaged: False'), # Short Line Railroad # Housing stats ('Houses remaining: 23', 'Houses remaining: 32') # 9 houses from light blues ] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Player was not eliminated properly. The following changes were made to the GameState:')
def __init__(self, settings, platformer_instance): GameState.__init__(self, settings) self.platformer_instance = platformer_instance self.keystate.update({ 'left':False, 'right':False, 'jump':False, 'up':False, 'down':False, }) self.font = pygame.font.Font(pygame.font.match_font("consolas", bold=True), 24)
def configure_keybindings(self): GameState.configure_keybindings(self) self.keydown_action_map.update({ QUIT: lambda: self.state_manager.set_current_state(GameStateManager.MAIN_MENU_STATE), PAUSE: lambda: None, SHOW_GRID: lambda: self.settings.set_show_grid(not self.settings.show_grid()), TOGGLE_3D: lambda: self.settings.set_draw_3d(not self.settings.draw_3d()) }) if self.settings.dev_mode(): self.keydown_action_map.update({ FREEZE_MODE: lambda: self.settings.set_frozen_mode(not self.settings.frozen_mode()) })
def __init__(self, gc): """Initialisation des ressources et des modèles qui ne doivent être initialisés qu'une seule fois""" GameState.__init__(self, gc) self.areas = {} self.area = None self.description_hash = {} # self.default_verb = 'look_at' # inside set_query_mode() self._verb = None # may not be needed self._complement = None self.set_query_mode(False) # ok?? self.inventory = Inventory() #Affichage de l'inventaire self.view.fillInventoryLayer(self.inventory) self.set_inventory_layer()
def __init__(self, player): """ Implementation of Monte Carlo Tree Search Creates a root of an MCTS tree to keep track of the information obtained throughout the course of the game in the form of a tree of MCTS nodes The data structure of a node consists of: - the game state which it corresponds to - w, the number of wins that have occurred at or below it in the tree - n, the number of plays that have occurred at or below it in the tree - expanded, whether all the children (legal moves) of the node have been added to the tree To access the node attributes, use the following format. For example, to access the attribute 'n' of the root node: policy = MCTSPolicy() current_node = policy.root policy.tree.node[current_node]['n'] """ self.digraph = nx.DiGraph() self.player = player self.num_simulations = 0 # Constant parameter to weight exploration vs. exploitation for UCT self.uct_c = np.sqrt(2) self.node_counter = 0 empty_board = GameState() self.digraph.add_node(self.node_counter, attr_dict={'w': 0, 'n': 0, 'uct': 0, 'expanded': False, 'state': empty_board}) empty_board_node_id = self.node_counter self.node_counter += 1 self.last_move = None if player is 'O': for successor in [empty_board.transition_function(*move) for move in empty_board.legal_moves()]: self.digraph.add_node(self.node_counter, attr_dict={'w': 0, 'n': 0, 'uct': 0, 'expanded': False, 'state': successor}) self.digraph.add_edge(empty_board_node_id, self.node_counter) self.node_counter += 1
def test_draw_card(self): state = GameState(1) player = state.players[0] # Test every card in both decks dict_card_types = { CHANCE_CARD: 'Chance', COMMUNITY_CHEST_CARD: 'Community Chest' } for card_type, card_str in dict_card_types.iteritems(): deck = state.decks[card_type] # Draw every card in the deck, check that cards are handled correctly # and that nothing else in the state is changed card = None for i in range(0, deck.size()): card = deck.peek() jail_free_count_before = player.jail_free_count str_before = str(state) expected_diff = None # initialized in the following if-block state.apply(GroupOfChanges([ GameStateChange.draw_card(deck, player)])) if card == LMBDA_GET_OUT_OF_JAIL_FREE: # Check that the card is not replaced on the deck, and that the # player's Jail Free card count is incremented. self.assertEqual(player.jail_free_count, jail_free_count_before + 1) for j in range(0, deck.size()): self.assertNotEqual(deck.draw(), LMBDA_GET_OUT_OF_JAIL_FREE) # Initialize. Used after this if-block to ensure that nothing else # in the state was changed. expected_diff = [ ('Jail free count: %d' % jail_free_count_before, 'Jail free count: %d' % player.jail_free_count) ] else: # Check that the card is replaced on the bottom if it is not the # Jail Free card. for j in range(0, deck.size() - 1): deck.draw() self.assertEqual(deck.draw(), card) # compare with last card # Initialize expected_diff = [] # Check that the rest of the state is unchanged by comparing the # string encodings of the GameStates str_after = str(state) self.assertDiffGameStates(str_before, str_after, expected_diff, msg='The GameState was not modified correctly')