Skip to content

Instantly share code, notes, and snippets.

@ProbonoBonobo
Created February 24, 2022 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProbonoBonobo/ba0b591a0bd5ccb5350b1edef9902c75 to your computer and use it in GitHub Desktop.
Save ProbonoBonobo/ba0b591a0bd5ccb5350b1edef9902c75 to your computer and use it in GitHub Desktop.
starter code to initialize an n-dimensional grid and populate it with variable-sized, non-intersecting ships
# battleship.py
# starter code to initialize an n-dimensional grid and populate it with variable-sized, non-intersecting ships
import random
class Board:
def __init__(self, dim=9):
self.dim = dim
self.grid = [[None for i in range(self.dim)] for j in range(self.dim)]
self.piece_sizes = (5, 4, 3, 3, 2)
self.guesses = set()
self.pieces = set()
self.initialize_fleet()
def initialize_fleet(self):
for size in self.piece_sizes:
placed = False
orientation = random.choice(
"hv"
) # representing this as a single bit (0 or 1) could simplify some of the logic below
# for dilating the board to include only valid placement opportunities, but much
# harder to follow that way
while not placed:
# we can automatically exclude starting coordinates that are too close to the boundary
x = random.randint(0, self.dim - size * int(orientation == "h"))
y = random.randint(0, self.dim - size * int(orientation == "v"))
coords = [
(x + i, y) if orientation == "h" else (x, y + i)
for i in range(size)
]
print(coords)
# we must also ensure that the piece doesn't intersect with any previously-placed ships. set intersection offers a
# convenient alternative to traversing the board and measuring strides
if not set(coords).intersection(self.pieces):
self.pieces.update(coords)
placed = True
print(f"Placed {coords}")
@property
def hits(self):
return self.pieces.intersection(self.guesses)
def __repr__(self):
return '
'.join([''.join([f"{' X ' if (i,j) in self.pieces else ' O '}" for i in range(self.dim)]) for j in range(self.dim)]) +"
"
if __name__ == '__main__':
p1 = Board()
print(p1)
"""
/home/kz/projects/pythonProject/venv/bin/python /home/kz/projects/nucamp/week3/tmp/battleship.py
[(4, 3), (5, 3), (6, 3), (7, 3), (8, 3)]
Placed [(4, 3), (5, 3), (6, 3), (7, 3), (8, 3)]
[(1, 1), (1, 2), (1, 3), (1, 4)]
Placed [(1, 1), (1, 2), (1, 3), (1, 4)]
[(7, 0), (7, 1), (7, 2)]
Placed [(7, 0), (7, 1), (7, 2)]
[(3, 2), (4, 2), (5, 2)]
Placed [(3, 2), (4, 2), (5, 2)]
[(6, 8), (7, 8)]
Placed [(6, 8), (7, 8)]
O O O O O O O X O
O X O O O O O X O
O X O X X X O X O
O X O O X X X X X
O X O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O X X O
...
... Process finished with exit code 0
... """
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment