working on a sample battleship game project in python
created a ship class for the various ships here
class Ship:
def __init__(self, ship_name, size, coordinates, direction):
self.ship_name = ship_name
self.size = size
self.coordinates = coordinates
self.direction = direction
here is my core battleship.py file:
from ship import Ship
SHIP_INFO = [
("Aircraft Carrier", 5),
("Battleship", 4),
("Submarine", 3),
("Cruiser", 3),
("Patrol Boat", 2)
]
BOARD_SIZE = 10
VERTICAL_SHIP = '|'
HORIZONTAL_SHIP = '-'
EMPTY = 'O'
MISS = '.'
HIT = '*'
SUNK = '#'
board=[]
for row in range(10):
board.append('O'*10)
def clear_screen():
print("\033c", end="")
def print_board_heading():
print(" " + " ".join([chr(c) for c in range(ord('A'), ord('A') + BOARD_SIZE)]))
def print_board(board):
print_board_heading()
row_num = 1
for row in board:
print(str(row_num).rjust(2) + " " + (" ".join(row)))
row_num += 1
def coord_prompt():
while True:
coords = input("Where do you want the ship + (example: A1)?: ")
coords_strip = coords.strip()
coords_lower = coords_strip.lower()
x = coords_lower[0]
y = coords_lower[1:]
if (len(x)+len(y)) in range(2,4):
if x not in 'abcdefghij' or y not in '1,2,3,4,5,6,7,8,9,10':
print("Oops! That was not a valid entry. Try again...")
continue
else:
return x,y
else:
if len(coords_lower) < 2 or len(coords_lower) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
def pos_prompt():
while True:
dir = input("[H]orizontal or [V]ertical?")
dir_strip = dir.strip()
dir_lower = dir_strip.lower()
if dir_lower not in 'hv':
print("Oops! That was not a valid entry. Try again...")
continue
else:
return dir_lower
def make_ships(player):
ships = []
for ship, size in SHIP_INFO:
coord_prompt()
pos_prompt()
ships.append(Ship(ship, size, (x, y), dir_lower))
return ships
player1 = input("What's Player 1's Name? ")
player2 = input("What's Player 2's Name? ")
print("\n")
print_board(board)
print("\n")
# define player one's fleet
make_ships(player1)
i'm getting the following error:
Traceback (most recent call last):
File "C:/Users/chrisstuart/Desktop/battleship/battleship/battleship.py", line 91, in <module>
make_ships(player1)
File "C:/Users/chrisstuart/Desktop/battleship/battleship/battleship.py", line 81, in make_ships
ships.append(Ship(ship, size, (x, y), dir_lower))
NameError: name 'x' is not defined
I just don't understand why the returned x and y variables from the coord_prompt function are not passing to the ship instance of Ship when running the make_ships function. I assumed it was a problem with the way that I had formatted some of the if statement and the while loop and tried a few variations but still getting same error.
coord_prompt()line, you're not getting the return values, try this instead:x, y = coord_prompt()