Start abstracting game into a class

This commit is contained in:
20241144010020 2024-12-03 11:37:01 -03:00
parent 393c1b23b4
commit 0ee1082c6d
1 changed files with 75 additions and 0 deletions

75
src/game.py Normal file
View File

@ -0,0 +1,75 @@
def make_board(size: int, filler = 0) -> list:
return [[filler for _ in range(size)] for _ in range(size)]
class Game:
def __init__(self, board_size: int, enemy_amount: int = 5) -> None:
self.my_ships = make_board(board_size)
# Two different boards, one to show your ships and one to show the places you have shot
self.hit_ships = make_board(board_size) # -1 = shot but not hit, 0 = not hit, 1 = hit
self.total_enemy_amount = enemy_amount
self.my_drawn_board = make_board(board_size + 1, " ")
self.enemy_drawn_board = make_board(board_size + 1, " ")
@property
def enemy_amount(self) -> int:
# Get the enemy amount based on the amount of ships that are not hit in the hit ships var
return self.total_enemy_amount - sum([row.count(1) for row in self.hit_ships])
def setup_drawn_board(self) -> None:
max_num_len = len(str(len(self.my_drawn_board) - 1))
# Currently inserts the columns and rows into the board
for i in range(len(self.my_drawn_board)):
for j in range(len(self.my_drawn_board[i])):
if i == 0 and j == 0:
self.my_drawn_board[i][j] = " " * max_num_len
elif i == 0:
self.my_drawn_board[i][j] = chr(j + 64)
elif j == 0:
self.my_drawn_board[i][j] = str(i).rjust(max_num_len)
else:
self.my_drawn_board[i][j] = " "
def draw_ships(self) -> None:
for i in range(len(self.ships)):
for j in range(len(self.ships[i])):
if self.ships[i][j] == 1:
self.my_drawn_board[i + 1][j + 1] = "B"
def draw_shots(self) -> None:
for i in range(len(self.hit_ships)):
for j in range(len(self.hit_ships[i])):
if self.hit_ships[i][j] == 1:
self.my_drawn_board[i + 1][j + 1] = "O"
if self.hit_ships[i][j] == -1:
self.my_drawn_board[i + 1][j + 1] = "X"
def draw_board(self) -> None:
for i in range(len(self.my_drawn_board)):
for j in range(len(self.my_drawn_board[i])):
print(self.my_drawn_board[i][j], end=" ")
print()
def draw(self) -> None:
self.draw_ships()
self.draw_shots()
self.draw_board()
def hit(self, x: int, y: int, state: int) -> None:
self.hit_ships[x][y] = state
def shoot(self, x: int, y: int) -> int:
"""Shot at own board and return hit or not hit"""
if self.ships[x][y] == 1:
return 1
return -1
na = Game(5)
na.setup_drawn_board()
na.ships[2][2] = 1
na.draw()