傳遞變量時一個類的實例在python對樣品戰艦遊戲項目工作NameError在Python
創造了船級的各種船舶這裏
class Ship:
def __init__(self, ship_name, size, coordinates, direction):
self.ship_name = ship_name
self.size = size
self.coordinates = coordinates
self.direction = direction
這裏是我的核心battleship.py文件:
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)
,我發現了以下錯誤:
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
我只是不明白爲什麼從coord_prompt函數返回的x和y變量在運行make_ships函數時沒有傳遞給Ship的ship實例。我認爲這是一個問題,我已經格式化了一些if語句和while循環,並嘗試了一些變體,但仍然得到相同的錯誤。
,是你的'coord_prompt()'行,你沒有得到的返回值,試試這個來代替: 'X,Y = coord_prompt()' – RichSmith