def test_move(self): # capturing move game = GameState() game.move_piece_to(game.square[2][1], 4, 1) game.move_piece_to(game.square[1][2], 2, 1) game.current_player = c.PLAYER2 game.selected = game.square[5][2] game.move(3, 0) # if catcher move again after move self.assertEqual(game.gamestage, c.SELECTED) self.assertEqual(game.square[4][1], None) self.assertEqual(game.selected, game.square[3][0]) self.assertTrue(game.is_catcher(game.selected)) dict1 = {(3, 0): game.square[3][0]} self.assertEqual(game.valid_moves, dict1) # non capturing move game = GameState() game.selected = game.square[2][1] self.assertEqual(game.square[3][0], None) game.move(3, 0) self.assertEqual(game.square[3][0].player, c.PLAYER1) self.assertTrue(game.square[2][1] is None) self.assertTrue(game.selected is None) self.assertTrue(game.gamestage, c.MOVED) self.assertFalse(game.valid_moves) # non valid move game.selected = game.square[1][2] game.move(2, 3) self.assertEqual(game.gamestage, c.NEW_TURN) self.assertFalse(game.valid_moves)
def setUp(self): self.state_1 = GameState(game_mode="Partner Eichel", offensive_player=1, active=0) self.state_2 = GameState(game_mode="Wenz", offensive_player=1, active=0) self.fixed_history_1 = ["E7_", "E8_", "E9_", "GO_", "H8_"] self.fixed_history_2 = ["EA_", "E10", "E8_", "HU_", "EU_"]
def run(): check_version() file_choice = choose_flashcard_file() create_pairs_table() name = ask_user_name() message_ask_for_second_half_pair, message_ask_for_first_half_pair, pairs_list = read_flashcards_set( file_choice, name) mode = ask_mode() turns_goal = ask_turns_goal() game = GameState(pairs_list, name, mode, turns_goal) time_start = time.time() # returns floating point number while True: game.current_turn += 1 make_scoreboard() turn_action = action_based_on_turns(game) if turn_action: # None evaluates to False fancy_print(turn_action) fancy_print("Turn number: %d. Good luck!" % game.current_turn) user_answer, true_answer = asks_user_question( game, message_ask_for_second_half_pair, message_ask_for_first_half_pair) check_if_want_quit_game(user_answer, time_start, game) evaluate_user_answer_spelling(true_answer, user_answer, game)
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 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 __init__(self, data, env_info={'state_space': None}): self.gamestate = GameState(data) self.returned_action = None self.done = False self.reward = 0 self.action_space = 5 self.state_space = 12 self.total, self.maximum = 0, 0 self.env_info = env_info self.player = self.gamestate.players[int(self.gamestate.you) - 1] # self.GameState.Player() self.snake_body = [ ] # snake body, add first element (for location of snake's head) if self.gamestate.players[0].id != self.player.id: self.dist = math.sqrt( (self.player.x - self.gamestate.players[0].x)**2 + (self.player.y - self.gamestate.players[0].y)**2) else: self.dist = math.sqrt( (self.player.x - self.gamestate.players[1].x)**2 + (self.player.y - self.gamestate.players[1].y)**2) self.prev_dist = 0 self.prev_body_len = 0 self.dead_enemies = DECEASED_ENEMIES # list with all deceased enemies
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 __init__(self, we_go_first, x, y): init_grid = [['e' for x in range(0, 15)] for x in range(0, 15)] if we_go_first: init_grid[x][y] = 'o' else: init_grid[x][y] = 'x' self.root = GameState(init_grid, x, y)
def test_leave_jail(self): state = GameState(1) player = state.players[0] # Test that leaving jail works no matter how many jail moves are left for num_turns in range(0, 3): # Set up player in jail state.apply(GroupOfChanges([GameStateChange.send_to_jail(player)])) # Decrement player's jail moves num_turns (0, 1, or 2) times for i in range(0, num_turns): state.apply( GroupOfChanges( [GameStateChange.decrement_jail_moves(player)])) # Test leaving jail, and ensure that player's jail moves are changed # correctly and that no other changes were made to the state. str_before = str(state) state.apply(GroupOfChanges([GameStateChange.leave_jail(player)])) str_after = str(state) expected_diff = [('Jail moves: %d' % (3 - num_turns), 'Jail moves: 0')] self.assertDiffGameStates(str_before, str_after, expected_diff, msg='Player did not leave jail properly')
def test_is_catcher(self): game = GameState() game.move_piece_to(game.square[1][0], 4, 1) self.assertTrue(game.is_catcher(game.square[5][0])) self.assertTrue(game.is_catcher(game.square[5][2])) self.assertFalse(game.is_catcher(game.square[2][1])) self.assertFalse(game.is_catcher(game.square[5][4]))
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 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_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() -> 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 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_correctly_display(self): """ Should return a correct fen-formatted description of the current game state. """ 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.player = 'b' g.castle_white_king = True g.castle_white_queen = True g.castle_black_king = True g.castle_black_queen = True g.en_passant = None g.halfmove_clock = 1 g.fullmove_number = 2 exp = 'rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2' self.assertEqual(g.fen, exp)
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 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 __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 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 test_get_possible_states(self): gs = GameState() res = [x.state for x in get_possible_states(gs, only_unique=False)] self.assertEqual(9, len(res)) self.assertTrue( array_in_array([["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]], res)) self.assertTrue( array_in_array([["-", "-", "-"], ["-", "X", "-"], ["-", "-", "-"]], res)) self.assertTrue( array_in_array([["-", "-", "-"], ["-", "-", "-"], ["-", "-", "X"]], res)) res = [x.state for x in get_possible_states(gs, only_unique=True)] self.assertEqual(3, len(res)) self.assertTrue( array_in_array([["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]], res)) self.assertTrue( array_in_array([["-", "-", "-"], ["-", "X", "-"], ["-", "-", "-"]], res)) self.assertFalse( array_in_array([["-", "-", "-"], ["-", "-", "-"], ["-", "-", "X"]], res))
def test_change_position_from_middle(self): state = GameState(1) player = state.players[0] # Set up player's initial position at Community Chest 2 state.apply( GroupOfChanges([ GameStateChange.change_position(player, INDEX[COMMUNITY_CHEST_2], state.bank, state.squares) ])) # Test player changing position to Water Works str_before = str(state) state.apply( GroupOfChanges([ GameStateChange.change_position(player, INDEX[WATER_WORKS], state.bank, state.squares) ])) str_after = str(state) expected_diff = [('Position: %d' % INDEX[COMMUNITY_CHEST_2], 'Position: %d' % INDEX[WATER_WORKS])] self.assertDiffGameStates( str_before, str_after, expected_diff, msg= 'Player was not moved from Community Chest 2 to Water Works properly' )
def backpropagation(self, last_visited, reward): """ Walk the path upwards to the root, incrementing the 'n' and 'w' attributes of the nodes along the way """ current = last_visited while True: self.digraph.node[current]['n'] += 1 self.digraph.node[current]['w'] += reward print('Updating to n={} and w={}:\n{}'.format( self.digraph.node[current]['n'], self.digraph.node[current]['w'], self.digraph.node[current]['state'])) # Terminate when we reach the empty board if self.digraph.node[current]['state'] == GameState(): break # Todo: # Does this handle the necessary termination conditions for both 'X' and 'O'? # As far as we can tell, it does # Will throw an IndexError when we arrive at a node with no predecessors # Todo: see if this additional check is no longer necessary try: current = self.digraph.predecessors(current)[0] except IndexError: break
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 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_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 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 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')
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 f(): if request.method == 'POST': data = request.get_json() print(data) state = [] me_moves = [] you_moves = [] your_move = None for i in range(256): state.append(int(data['Inputs']['input1'][0][str(i + 1)])) if int(data['Inputs']['input1'][0][str(i + 1)]) == 1: me_moves.append((i // 16, i % 16)) if int(data['Inputs']['input1'][0][str(i + 1)]) == -1: you_moves.append((i // 16, i % 16)) if len(me_moves) == 0: game = GameState() origin = None if len(you_moves) > 0: your_move = you_moves[0] if len(you_moves) > 1: return 'Error: you_moves > 1' else: game = pickle.load(open('game.pkl', 'rb')) origin = pickle.load(open('origin.pkl', 'rb')) pre_state = pickle.load(open('state.pkl', 'rb')) your_move = None for i in range(16): for j in range(16): if state[i * 16 + j] != pre_state[i * 16 + j] and state[ i * 16 + j] == -1: if your_move != None: return 'Error: your_move not none' your_move = (i, j) if your_move != None: print('Moved', your_move) game.move(*your_move) player_icon = None if len(me_moves) == len(you_moves): player_icon = 'X' elif len(me_moves) == (len(you_moves) - 1): player_icon = 'O' else: return 'Error: no player icon' recom_moves = predict(state, model_name='gomoku_nas.hdf5') print(recom_moves) print(origin) print(game) tar, tree = MCTSPolicy(player=player_icon).move( game, recom_moves, 100, origin) game.move(*tar) print(game) pickle.dump(game, open('game.pkl', 'wb')) pickle.dump(tree, open('origin.pkl', 'wb')) state[tar[0] * 16 + tar[1]] = 1 pickle.dump(state, open('state.pkl', 'wb')) return str(tar[0] * 16 + tar[1])