将变量传递给Python中的类实例时的NameError

时间:2017-03-03 14:46:14

标签: python

在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

我只是不明白为什么在运行make_ships函数时,coord_prompt函数返回的x和y变量没有传递给Ship的ship实例。我认为这是一个问题,我已经格式化了一些if语句和while循环并尝试了一些变化,但仍然得到相同的错误。

1 个答案:

答案 0 :(得分:2)

因为您还没有在调用函数中捕获返回值,以便在后续调用中使用它们。

名称xy本地coord_prompt,并且在该功能完成后不会保留。返回值,但您仍需要将它们分配给某些内容。从pos_prompt返回的值也是如此。

    x, y = coord_prompt()
    dir_lower = pos_prompt()
    ships.append(Ship(ship, size, (x, y), dir_lower))