battleship

py

School

University Of Arizona *

*We aren’t endorsed by this school

Course

120

Subject

Computer Science

Date

Dec 6, 2023

Type

py

Pages

4

Uploaded by CommodoreFire8688

Report
""" name: battleship.py author: Launa sigars prupose: the purpose of this game is to create a 2d list grid with the\ 5 ships sizes/types and positions to allow us to play the game battleships\ then we can create a guesses and player 1 function that allow us\ to guess the positions with different arangments provided and errors given\ then telling us hit, miss or agian and or allowing us to give just the\ type,x1 or y1 when guessing. class: csc 120 """ import sys class GridPos: def __init__(self, x, y): """ so the x and the y peraeters repersent corriadents of the ships\ then the ship set to None indicate that there is no ship at this\ position and finally guessed is a boolean set to false but updated\ later on. """ self.x = x self.y = y self.ship = None self.guessed = False def __str__(self): return f"({self.x}, {self.y})" class Board: def __init__(self): """ this class creates our grid for the game battleship\ starting with a 2d list and having 10 has the final length\ with the corridants inside to make the final grid. """ self.grid = [] self.ships = [] grid = [] for x in range(10): row = [] for y in range(10): row.append(GridPos(x, y)) grid.append(row) self.grid = grid def process_guess(self, x, y): """ this function Checks if the guess is legal\ Checks if the position has been guessed before\ Checks if the game is over and Processes a new guess\ where is processes a miss or a hit. having the preameters of\ self, x and y which these being the guesses. """ if x < 0 or x > 9 or y < 0 or y > 9: print("illegal guess")
return pos = self.grid[x][y] if pos.guessed: if pos.ship is None or (pos.ship and pos.ship.hits == 0): print("miss (again)") else: print("hit (again)") else: pos.guessed = True if pos.ship is None: print("miss") else: ship = pos.ship ship.hits += 1 if ship.hits == ship.size: print(f"{ship.type} sunk") self.ships.remove(ship) for position in ship.positions: self.grid[position[0]][position[1]].ship = None else: print("hit") if len(self.ships) == 0: print("all ships sunk: game over") sys.exit(0) def __str__(self): result = [] for x in range(10): row = [] for y in range(10): row.append(str(self.grid[x][y])) result.append(" ".join(row)) return "\n".join(result) class Ship: def __init__(self, type, size, x1, y1, x2, y2): """ where type repersents the ship, size being the acutal length of the\ ship , position is where the ship is on the grid created earlier\ and finally hits is how many times we hit it. """ self.type = type self.size = size self.positions = [] self.hits = 0 if x1 == x2: for y in range(y1, y2 + 1): self.positions.append((x1, y)) else: for x in range(x1, x2 + 1): self.positions.append((x, y1)) def __str__(self): return f"{self.type}: {self.positions}" def read_guesses(file_name):
""" Opens a file: The function opens a file with \ the name file_name and reads its lines. \ Processes each line: For each line \ in the file, it does the following.\ Returns the guesses: Finally, it returns \ the list of tuples, where each tuple represents a guess. """ file = open(file_name, 'r') lines = file.readlines() guesses = [] for line in lines: parts = line.strip().split() if len(parts) == 2: x = int(parts[0]) y = int(parts[1]) guesses.append((x, y)) return guesses def read_ship_placements(file_name, grid): """ Opens a file: The function opens a file with the name \ file_name and reads its lines. Checks fleet \ composition: It checks if the file contains \ exactly 5 lines. If not, it prints an \ error message and exits the program finally\ returing the ship list. """ file = open(file_name, 'r') lines = file.readlines() if len(lines) != 5: print("ERROR: fleet composition incorrect") sys.exit(0) ships = [] # Define the expected sizes for each ship type expected_sizes = {"A": 5, "B": 4, "S": 3, "D": 3, "P": 2} for line in lines: parts = line.strip().split() if len(parts) != 5: print(f"ERROR: incorrect input: {line}") sys.exit(0) type = parts[0] x1 = int(parts[1]) y1 = int(parts[2]) x2 = int(parts[3]) y2 = int(parts[4]) if type not in expected_sizes: print(f"ERROR: incorrect ship type: {line}") sys.exit(0)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
if x1 < 0 or x1 > 9 or y1 < 0 or y1 > 9 or \ x2 < 0 or x2 > 9 or y2 < 0 or y2 > 9: print(f"ERROR: ship out-of-bounds: {line}") sys.exit(0) if x1 != x2 and y1 != y2: print(f"ERROR: ship not horizontal or vertical: {line}") sys.exit(0) if x1 == x2: size = abs(y2 - y1) + 1 else: size = abs(x2 - x1) + 1 # Compare the calculated size with the expected size if size != expected_sizes[type]: print(f"ERROR: incorrect ship size: {line}") sys.exit(0) # Check for overlapping ship positions for ship in ships: for position in ship.positions: if position in Ship(type, size, x1, y1, x2, y2).positions: print(f"ERROR: overlapping ship: {type} \ {position[0]} {position[1]} {x2} {y2}") sys.exit(0) new_ship = Ship(type, size, x1, y1, x2, y2) ships.append(new_ship) # Update GridPos objects with the new ship for i in range(min(x1, x2), max(x1, x2) + 1): for j in range(min(y1, y2), max(y1, y2) + 1): grid[i][j].ship = new_ship return ships def main(): placement_file = input() guess_file = input() board = Board() board.ships = read_ship_placements(placement_file, board.grid) guesses = read_guesses(guess_file) for guess in guesses: board.process_guess(guess[0], guess[1]) if __name__ == "__main__": main()