def set_board(self, player_num): if player_num == 1: self.board = Board(Square(20, 100), Square(380, 460)) elif player_num == 2: self.board = Board(Square(460, 100), Square(820, 460)) self.board.squares_not_shot_list() self.board.available_squares_dict(self)
def create_from_string(round_num: int, game_phase: GamePhase) -> 'Board': """ This method takes a string (that is a representation of the board in x-y format) and returns a board object. This also defines the round number and the game phase for the board. """ new_board: Board = Board(None, round_num, game_phase) for row_i in range(Board._NUM_ROWS): row_string: List[str] = input().split(" ") for col_i, char in enumerate(row_string): pos: Pos2D = Pos2D(col_i, row_i) if (char == SquareState.CORNER.get_representation()): new_board.squares[pos] = \ Square(pos, None, SquareState.CORNER) elif (char == SquareState.OPEN.get_representation()): new_board.squares[pos] = \ Square(pos, None, SquareState.OPEN) elif (char == Player.WHITE.get_representation()): new_board.squares[pos] = \ Square(pos, Piece(Player.WHITE), SquareState.OCCUPIED) elif (char == Player.BLACK.get_representation()): new_board.squares[pos] = \ Square(pos, Piece(Player.BLACK), SquareState.OCCUPIED) return new_board
def load(app, filename=None, from_memory=None): if filename is None and from_memory is None: filename = filedialog.askopenfilename(initialdir="~/Desktop", title="Select file", filetypes=(("json files", "*.json"), ("all files", "*.*"))) if from_memory is None and '.json' in filename: with open(filename, 'rb') as myfile: r = myfile.read() myfile.close() r = json.loads(r) elif from_memory is not None: r = from_memory else: return grid = r["grid"] saved_sprites = r["sprites"] tux = r["tux"] screen_rows = [] i = 0 canvas = app.screen.canvas canvas.delete("all") for file_row in grid: screen_rows.append([]) for cell in file_row: # def __init__(self, row, column, canvas, app, g=constants.grid_size, square_type='grass') s = Square(row=int(cell["row"]), column=int(cell["column"]), app=app, canvas=canvas, square_type=cell["square_type"]) # def add_feature(self, feature, app, required_type="grass"): if cell["has_tree"] == "True": s.add_feature(feature="tree", app=app) if cell["has_rock"] == "True": s.add_feature("rock", app=app) screen_rows[i].append(s) i += 1 app.screen.grid = screen_rows app.tux = sprites.Tux(app, x=tux["column"], y=tux["row"]) app.sprites = [] s = app.sprites for sprite in saved_sprites: # def __init__(self, app, x=None, y=None) x = sprite["column"] y = sprite["row"] if sprite["type"] == "virus": s.append(sprites.Monster(app=app, x=x, y=y)) l = len(s) - 1 s[l].ind = l app.screen.grid[y][x].occupied = True elif sprite["type"] == "fish": s.append(sprites.Fish(app=app, x=x, y=y)) l = len(s) - 1 s[l].ind = l
def get_board(self): """creates a list of all the board's squares""" board = [] for x in range(self.start.x, self.end.x + 1, Square.length): for y in range(self.start.y, self.end.y + 1, Square.length): board.append(Square(x, y)) return board
def _init_squares() -> Dict[Pos2D, Square]: """ This method initializes all square objects for a complete board as if it were the beginning of the game. """ squares: Dict[Pos2D, Square] = {} for col_i in range(Board._NUM_COLS): for row_i in range(Board._NUM_ROWS): pos: Pos2D = Pos2D(col_i, row_i) if (pos.x == 0 and (pos.y == 0 or pos.y == Board._NUM_ROWS - 1) or pos.x == Board._NUM_COLS - 1 and (pos.y == 0 or pos.y == Board._NUM_ROWS - 1)): squares[pos] = Square(pos, None, SquareState.CORNER) else: squares[pos] = Square(pos, None, SquareState.OPEN) return squares
def place_ship(player, ship, ship_start, ship_end): """places a ship with square coordinates defined by the player, and checks if the ship is placed in a valid place, correct size and inside the board""" ship_start_x = min(ship_start.x, ship_end.x) ship_end_x = max(ship_start.x, ship_end.x) ship_start_y = min(ship_start.y, ship_end.y) ship_end_y = max(ship_start.y, ship_end.y) not_available_squares = [] for key in player.board.squares_availability: if player.board.squares_availability[key] == 0: not_available_squares.append(key) try: assert player.board.start.x <= ship_start.x <= player.board.end.x and \ player.board.start.y <= ship_start.y <= player.board.end.y except AssertionError: return "Can't place ship outside of board" if ship_start.x != ship_end.x and ship_start.y != ship_end.y: return "Invalid ship coordinates. Ship must be placed horizontally or vertically." elif ship_start.x == ship_end.x or ship_start.y == ship_end.y: if (ship_end_y - ship_start_y) / Square.length > ship.size - 1 or \ (ship_end_x - ship_start_x) / Square.length > ship.size - 1: return "Ship is too long! must be %d squares long." % ship.size elif (ship_end_y - ship_start_y) / Square.length < ship.size - 1 and \ (ship_end_x - ship_start_x) / Square.length < ship.size - 1: return "Ship is too short! must be %d squares long." % ship.size for x in range(ship_start_x, ship_end_x + 1, Square.length): for y in range(ship_start_y, ship_end_y + 1, Square.length): if (x, y) in not_available_squares: return "Can't place ship on top or next to another ship." else: ship.set_position(player, Square(ship_start_x, ship_start_y), Square(ship_end_x, ship_end_y)) for x in range(ship_start_x - Square.length, ship_end_x + Square.length + 1, Square.length): for y in range(ship_start_y - Square.length, ship_end_y + Square.length + 1, Square.length): if (x, y) in player.board.squares_availability: player.board.squares_availability[(x, y)] = 0 return "success"
def __init__(self, app, height=constants.bounds["y"][1], width=constants.bounds["x"][1], grid=constants.grid_size): self.h = height self.g = grid self.w = width self.monsters = [] self.fishes = [] self.fires = [] self.canvas = Canvas(app.frame, height=self.h + 10, width=self.w + 10, background="green") self.grid = [] self.grids = [] self.app = app for i in range(0, 20): self.grids.append([]) for j in range(0, 20): self.grids[i].append({}) self.current_map = {} self.current_map["x"] = random.randint(0, 19) self.current_map["y"] = random.randint(0, 19) app.starting_map = self.current_map.copy() for i in range(0, (int(self.h / self.g))): self.grid.append([]) # print app.grid[i] for j in range(0, (int(self.w / self.g))): r = random.randint(0, 12) if r % 11 == 0: square_type = 'water' elif r % 4 == 0 and self.neighbor_type( i, j, square_type='water'): square_type = 'water' else: square_type = 'grass' s = Square(i, j, self.canvas, app=app, square_type=square_type) self.grid[i].append(s) y = self.current_map["y"] x = self.current_map["x"]
def color_ship(screen, ship, color): """colors a whole ship a certain color""" for x in range(ship.start_x, ship.end_x + 1, Square.length): for y in range(ship.start_y, ship.end_y + 1, Square.length): BoardUI.color_square(screen, Square(x, y), color)
def rand_place_ships(player): """randomly places the ship on the opponent's board""" try_again = True ship_start_x = None ship_end_x = None ship_start_y = None ship_end_y = None while try_again is True: player.board.available_squares_dict(player) player.board.ship_pos = {} temp = 0 for ship in player.board.ships: not_done = True # used to create the loop that searches for a valid and available ship's coordinates ship_end = Square(0, 0) # initializes the ship's end square that will be randomized inside the loop m = ship.m_factor # the factor that's used to check if the ship's end will not exceed the board available_squares = [ ] # all the squares that are available to place a ship on not_available_squares = [ ] # all the squares that are not available to place a ship on for key in player.board.squares_availability: if player.board.squares_availability[key] == 1: available_squares.append( Square(key[0], key[1])) # adds the relevant squares to the # available_squares list elif player.board.squares_availability[key] == 0: not_available_squares.append( key ) # adds the relevant squares to the not_available_squares list while not_done: # loops to search for an available place to place the ship check = [] ship_start = random.choice( available_squares ) # randomly chooses the ship's start from the # available squares temp += 1 def is_valid(value, axis): if axis == 'x': return player.board.start.x + m * Square.length <= value <= player.board.end.x - \ m * Square.length elif axis == 'y': return player.board.start.y + m * Square.length <= value <= player.board.end.y - \ m * Square.length if is_valid(ship_start.x, axis='x'): ship_end.x = random.choice([ ship_start.x - m * Square.length, ship_start.x, ship_start.x + m * Square.length ]) elif player.board.start.x + m * Square.length <= ship_start.x: ship_end.x = random.choice( [ship_start.x - m * Square.length, ship_start.x]) else: ship_end.x = random.choice( [ship_start.x, ship_start.x + m * Square.length]) # checks where the ship has enough place to be placed horizontally (if it's too close to the left # or the right of the board) and chooses the ship's end accordingly if ship_start.x != ship_end.x: ship_end.y = ship_start.y else: if is_valid(ship_start.y, axis='y'): ship_end.y = random.choice([ ship_start.y - m * Square.length, ship_start.y + m * Square.length ]) elif player.board.start.y + m * Square.length <= ship_start.y: ship_end.y = ship_start.y - m * Square.length else: ship_end.y = ship_start.y + m * Square.length # checks where the ship has enough place to be placed vertically (if it's too close to the start # or the bottom of the board) and chooses the ship's end accordingly ship_start_x = min(ship_start.x, ship_end.x) ship_end_x = max(ship_start.x, ship_end.x) ship_start_y = min(ship_start.y, ship_end.y) ship_end_y = max(ship_start.y, ship_end.y) for x in range(ship_start_x, ship_end_x + 1, Square.length): for y in range(ship_start_y, ship_end_y + 1, Square.length): if (x, y) in not_available_squares: check.append('no') if len(check) == 0: not_done = False # stops the loop if all the coordinates are available # checks if the chosen ship coordinate's is available and not placed on or next to another ship try_again = False elif temp > 500: not_done = False try_again = True ship.set_position(player, Square(ship_start_x, ship_start_y), Square(ship_end_x, ship_end_y)) # calls the set_position method to save the ship's coordinates accordingly for x in range(ship_start_x - Square.length, ship_end_x + Square.length + 1, Square.length): for y in range(ship_start_y - Square.length, ship_end_y + Square.length + 1, Square.length): if (x, y) in player.board.squares_availability: player.board.squares_availability[(x, y)] = 0
def generate_screen(self, from_dir): self.canvas.delete("all") self.app.screen.monsters = None self.app.screen.monsters = [] self.app.screen.fishes = None self.app.screen.fishes = [] self.app.sprites = None self.app.sprites = [] print('generate_screen') print(self.app.screen.fishes) # print(self) g = self.grid.copy() # delete(self.grid) h = len(g) w = len(g[0]) # m = self.monsters.copy() # f = self.fishes.copy() new_grid = [] for i in range(0, h): new_grid.append([]) for j in range(0, w): if from_dir == "Down" and i == 0: source_square = g[-1][j] square_type = source_square.square_type elif from_dir == "Up" and i == h - 1: source_square = g[0][j] square_type = source_square.square_type elif from_dir == "Left" and j == w - 1: source_square = g[i][0] square_type = source_square.square_type elif from_dir == "Right" and j == 0: source_square = g[i][-1] square_type = source_square.square_type else: r = random.randint(0, 12) if r % 11 == 0: square_type = 'water' elif r % 12 == 1: if abs(self.current_map["y"] - self.app.starting_map["y"] ) > 10 or self.current_map["y"] < 5: square_type = 'snow' elif abs(self.current_map["y"] - self.app.starting_map["y"]) < 10: square_type = 'sand' elif r % 4 == 0: if self.neighbor_type(i, j, square_type='water'): square_type = 'water' elif self.neighbor_type(i, j, square_type='snow'): square_type = 'snow' elif self.neighbor_type(i, j, square_type='sand'): square_type = 'sand' else: square_type = 'grass' else: square_type = 'grass' if self.current_map["x"] == 0 and j == 0: square_type = 'water' if self.current_map["y"] == 0 and i == 0: square_type = 'water' try: s = Square(i, j, self.canvas, app=self.app, square_type=square_type) except: print("r=", r) raise Exception("Boom") new_grid[i].append(s) return new_grid