Files
battleship/battleship/human.py
2022-04-25 17:37:04 -07:00

57 lines
1.9 KiB
Python

from __future__ import annotations
from typing import List
from .bs_types import Coordinate
from .player import Player, PlacementError
from .ship import Ship, ShipType
from .ui import read_coordinate, format_board, player_cell_fn, read_orientation, opponent_cell_fn, \
clear_screen
class HumanPlayer(Player):
def place_ships(self, ship_types: List[ShipType]):
print(f"{self.name}, time to place your ships. Press ENTER to continue.")
input()
super().place_ships(ship_types)
clear_screen()
def place_ship(self, ship_type: ShipType) -> Ship:
current_board = format_board(player_cell_fn(self), self.board)
while True:
clear_screen()
print(current_board)
print()
print(f"Please place your {ship_type.name} (size {ship_type.size}).")
coord = read_coordinate(f"What is the top left coordinate of the ship? ", self.board)
orientation = read_orientation("Does the ship extend [D]own or to the [R]ight? ")
print()
ship = Ship(coord, ship_type, orientation)
try:
self.validate_placement(ship)
return ship
except PlacementError as e:
print(e.message + "\n")
print("Press ENTER to try again.\n")
input()
def guess(self, opponent: Player) -> Coordinate:
current_board = format_board(opponent_cell_fn(self, opponent), opponent.board)
while True:
clear_screen()
print(current_board)
print()
coord = read_coordinate(f"{self.name}, where would you like to aim your cannons? ", opponent.board)
if coord not in self.guesses:
return coord
print("You've already tried that coordinate!")
print("Press ENTER to try again.\n")
input()