Python: NameError: 全局名称'lol'未定义
我知道这个问题有很多人问过,但我找了一个小时都没找到解决办法。
ship2X=eg.passwordbox("Player " + str(playerNumber) + " input the x co-ordinate for your SECOND ship ")
ship2Y=eg.passwordbox("Player " + str(playerNumber) + " input the y co-ordinate for your SECOND ship ")
return[ship2X, ship2Y]
上面的代码是在一个函数里面。
def haveShot(playerNumber, ship, ship2, board):
global ship2
eg.msgbox("Player " + str(playerNumber) + " your shot")
hit=False
shotX=eg.enterbox("Enter the x-coordinate for your shot: ")
shotY=eg.enterbox("Enter the y-coordinate for your shot: ")
.... 这里有错误检查....
if int(shotX) == int(ship[0]) and int(shotY) == int(ship[1]):
board[5 - int(shotY)][int(shotX) - 1] = "X"
eg.msgbox("Nice shot! You hit ship 1")
hit = True
elif int(shotX) == int(ship2[0]) and int(shotY) == int(ship2[1]):
board[5 - int(shotY)][int(shotX) - 1] = "X"
eg.msgbox("Nice shot! You hit ship 2")
hit = True
elif board[5 - int(shotY)][int(shotX) - 1] == "o":
eg.msgbox("You already tried that shot! D'oh!")
else:
board[5 - int(shotY)][int(shotX) - 1] = "o"
eg.msgbox("Unlucky - you missed!")
是的,我在这之前有一个if语句。
然后在快结束的时候我有这个:
hit = False
winner = "0"
p1 = 0
p2 = 0
while hit == False:
hit = haveShot("1", player2Ship, player2Ship, player1Board)
if hit:
p1 = p1+1
hit = haveShot("2", player1Ship, player1Ship, player2Board)
if hit:
p2 = p2+2
我从第一个输入船的地方复制过来的,所以我真的很困惑为什么会出现这个问题...
有什么想法吗?
如果你想看完整的代码,可以在这里查看:http://pastebin.com/TAyHtnTs
我遇到的错误是,如果我输入第二艘船的正确坐标,它却说我没击中,然而如果我输入第一艘船的正确坐标,它却说我击中了,像应该的那样。
谢谢你能提供的帮助 :)
2 个回答
0
我没有足够的声望来评论,要不然我会的,不过...
你没有定义“lol”,你定义的是“lolX”和“lolY”,它们是不同的变量。
如果你想定义一个包含值的列表或字典,你不能只写 lolX 或 lolY,你需要这样做(我这里用字典,因为这似乎是你想要的):
lol = {}
lol[X] = eg.passwordbox("玩家 " + str(playerNumber) + " 输入你第二艘船的 x 坐标 ")
这样你就可以通过 lol[X] 来访问 lol 中的值。
你定义的是不同的变量,而不是定义这个变量的具体值。
0
几点注意事项:
第81行
你不能有两个连续的返回语句。第一个返回会让函数结束。如果你想返回两组坐标,可以返回一个嵌套列表:
return [[x1, y1], [x2, y2]]
第161行
然后使用解包来获取这些值:
p1ship1, p1ship2 = inputCoords("1")
p2ship1, p2ship2 = inputCoords("2")
第171/176行
确保你传入的两个船是不同的(目前它们是一样的):
hit = haveShot("1", player2Ship, player2Ship, player1Board)
到
hit = haveShot("1", p2ship1, p2ship2, player1Board)
第170行
while hit == False
这个条件意味着一旦玩家1的船被击中,游戏就会结束。可以使用另一个变量来检查游戏是否结束,比如:
while player1ShipCount > 0 and player2ShipCount > 0:
#play game
并且要记录每个玩家可用的船只情况。