def test_position(): p1 = Position(1, 2) p2 = p1.copy() assert p1 == p2 p1.x = 4 assert p2.x == 1 assert p2.y == 2 assert p1 != p2
def find_elements_in_bbox(bbox): grass = Grass() return [ Element(position=Position(567234, 567234), ui_element=grass, polygon=None, center=Position(567234, 567234)) ]
def next_position(self): b = self._board legal_positions = b.legal_positions() # Loop forever until valid input. while True: try: print("Row : ", end="") row = _parse_input_num(input()) print("Column : ", end="") column = _parse_input_num(input()) pos = Position(row, column) for legal_pos in legal_positions: if pos == legal_pos: return pos print("This pos is occupied. Try again.") continue except KeyboardInterrupt: print("Aborted due to Ctrl-C.") import sys sys.exit() except: print("Unexpected error due to invalid input. Try again.")
def convert_states_to_model_features(config, states): rewards_np = np.zeros([len(states)]) positions_np = np.zeros([len(states), config.rows * config.columns]) # 3 is the number of feature planes. boards_np = np.zeros([len(states), 3, config.rows, config.columns]) for i, state in enumerate(states): # Labels rewards_np[i] = state.reward j = config.convert_position_to_index(state.position) positions_np[i][j] = 1.0 # Features assert isinstance(state.next_player_color, Color) if state.next_player_color == Color.BLACK: boards_np[i, 2, :, :] = 1.0 snapshot = state.snapshot for x in range(config.rows): for y in range(config.columns): color = snapshot.get(Position(x, y)) if color is None: continue if color == Color.BLACK: boards_np[i, 0, x, y] = 1.0 else: assert color == Color.WHITE boards_np[i, 1, x, y] = 1.0 # Puts channels at the end. boards_np = np.transpose(boards_np, [0, 2, 3, 1]) return boards_np, (rewards_np, positions_np)
def convert_inference_state_to_model_feature(config, inference_state): # 3 is the number of feature planes. boards_np = np.zeros([1, 3, config.rows, config.columns]) assert isinstance(inference_state.next_player_color, Color) if inference_state.next_player_color == Color.BLACK: boards_np[0, 2, :, :] = 1.0 snapshot = inference_state.snapshot for x in range(config.rows): for y in range(config.columns): color = snapshot.get(Position(x, y)) if color is None: continue if color == Color.BLACK: boards_np[0, 0, x, y] = 1.0 else: assert color == Color.WHITE boards_np[0, 1, x, y] = 1.0 # Puts channels at the end. boards_np = np.transpose(boards_np, [0, 2, 3, 1]) return boards_np
def handle_select(pos): # Handles mouse button down event. # Sets the selected_piece if a piece is selected nonlocal selected_piece selected_piece = None pos = pos[0] - BOARD_OFFSETS[0], pos[1] - BOARD_OFFSETS[1] if 0 <= pos[0] < BOARD_SIZE[0] and 0 <= pos[1] < BOARD_SIZE[1]: position = Position(pos[0] // TILE_SIZE, pos[1] // TILE_SIZE) selected_piece = board.get_piece(position)
def draw(self): """Draws pieces on the board""" for (x, y) in product(range(8), range(8)): piece = self.board.find_piece(Position(x, y)) if piece.color != None: self.buttons[x][y].config( text=Gui.piece_type_dict[piece.type][piece.color]) else: self.buttons[x][y].config(text='')
def test_snake_move(): snake = Snake(3, 3, Position(1, 1), Direction.RIGHT) snake.move(None) assert snake.head.current_position.x == 2 assert snake.head.current_position.y == 1 assert snake.direction == Direction.RIGHT snake.move(Direction.UP) assert snake.head.current_position.x == 2 assert snake.head.current_position.y == 0 assert snake.direction == Direction.UP
def select_piece(self): """Select piece to move""" color = self.board.turn_color for x, rows in enumerate(self.buttons): for y, button in enumerate(rows): piece = self.board.find_piece(Position(x, y)) if piece.color == color and \ piece.moves != [] and \ piece.moves != None: func = partial(self.show_moves, piece) button.configure(command=func)
def test_empties(self): othelloGame = OthelloGame(board_size=6) initial = othelloGame.initial_game() perimeter = othelloGame.perimeter_positions(initial) border = [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)] border_positions = set([ Position(x_position=x, y_position=y, board_size=6) for x, y in border ]) self.assertEqual(border_positions, set(perimeter))
def test_corner_neighbors(self): game = OthelloGame(board_size=6) a_position = game.new_position(5, 5) neighbors = set(game.get_neighbors(a_position)) valid_neighbors = [(5, 4), (4, 4), (4, 5)] true_neighbors = set([ Position(x_position=x, y_position=y, board_size=6) for x, y in valid_neighbors ]) self.assertEqual(neighbors, true_neighbors)
def handle_drop(pos): # Handles mouse button up event. # Moves the selected_piece if to specified position if allowed. # Specified position must be an empty position! nonlocal selected_piece pos = pos[0] - BOARD_OFFSETS[0], pos[1] - BOARD_OFFSETS[1] if 0 <= pos[0] < BOARD_SIZE[0] and 0 <= pos[1] < BOARD_SIZE[1]: click_position = Position(pos[0] // TILE_SIZE, pos[1] // TILE_SIZE) if selected_piece: possible_pos = board.can_move(selected_piece, click_position) if possible_pos: board.move(selected_piece, possible_pos)
def test_get_neighbors(self): game = OthelloGame(board_size=6) a_position = game.new_position(2, 2) neighbors = set(game.get_neighbors(a_position)) valid_neighbors = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)] true_neighbors = set([ Position(x_position=x, y_position=y, board_size=6) for x, y in valid_neighbors ]) self.assertEqual(neighbors, true_neighbors)
def test_snake_calc_next_head_postion(): snake = Snake(3, 3, Position(1, 1), Direction.RIGHT) position = snake._calc_next_head_position(Direction.RIGHT) assert position.x == 2 assert position.y == 1 position = snake._calc_next_head_position(Direction.LEFT) assert position.x == 0 assert position.y == 1 position = snake._calc_next_head_position(Direction.UP) assert position.x == 1 assert position.y == 0 position = snake._calc_next_head_position(Direction.DOWN) assert position.x == 1 assert position.y == 2
def next_position(self): b = self._board # Loop forever until valid input. while True: try: print("Column : ", end="") column = int(input()) row = b.next_available_row(column) if row == -1: print("This column is full. Try again.") continue return Position(row, column) except KeyboardInterrupt: print("Aborted due to Ctrl-C.") import sys sys.exit() except: print("Unexpected error due to invalid input. Try again.")
def draw(self): """Draws the board configuration in the terminal""" display = " a b c d e f g h \n" + \ "________________________________ \n " # Loop over all x and y indices for j in range(8): display += " " + str(j + 1) + "|" for i in range(8): # Find the piece index for position [i, j] position_ij = Position(i, j) piece = self.board.find_piece(position_ij) if piece.color != None: display += " " + \ Ui.piece_type_dict[piece.type][piece.color] + " " else: # Draw an empty cell display += " - " # New line for different i value display += "|" + str(j + 1) + " \n " display += "_______________________________ \n" + \ " a b c d e f g h \n" self.board_string = display print(display)
def start(): char_position = Position(x=567234, y=567234) bbox = Bbox.from_position(char_position) viewport = Viewport(bbox) pygame.init() window = pygame.display.set_mode((28 * TILE_SIZE, 21 * TILE_SIZE)) sprites = load_sprites() loop = True while loop: pygame.time.Clock().tick(30) for event in pygame.event.get(): if event.type == QUIT: loop = False elif event.type == KEYDOWN: if event.key == K_RIGHT: print("key right pressed") elif event.key == K_LEFT: print("key left pressed") elif event.key == K_UP: print("key up pressed") elif event.key == K_DOWN: print("key down pressed") elements = find_elements_in_bbox(viewport.bbox) for _, element in enumerate(elements): window.blit( sprites, viewport.convert_position(element.position).to_tuple(), element.get_sprites_rect()) pygame.display.flip()
def test_initialization(self): with self.assertRaises(InvariantException): Position(x_position=47, y_position=1, board_size=6)
def test_asserts(self): self.assertTrue(Position.position_logic(1, 2, 5)) self.assertFalse(Position.position_logic(48, 2, 6)) self.assertTrue(Position.position_logic(2, 3, 66))
def coordinate2position(self, coordinate: str) -> Position: """Converts user input to a board position""" x = Ui.x_str2int[coordinate[0]] y = Ui.y_str2int[coordinate[1]] return Position(x, y)