所以我正在开发一款游戏,这是我目前的代码,工作正常:
print("Type directions() to see commands" )
def directions() :
print("Type North, East, South or West to move" )
move = input("North, East, South or West? ")
if move == "North":
north()
elif move == "East":
east()
elif move == "South":
south()
elif move == "West":
west()
def north():
print("You moved North")
x=0
x=(x+1)
print("You are at co-ordinates", x, "x:0 y" )
但是,我知道稍后会出现问题,因为x会针对每个方向重置。将x=0
放在代码顶部并将其从def north()
部分删除时,在运行代码时,Python会给出错误:
'UnboundLocalError:在赋值'
之前引用的局部变量'x'
我如何对此进行编码,以便'x'开头为0,但可以通过def
函数进行更改?
答案 0 :(得分:1)
您可以执行以下两项操作之一:使用全局变量(应避免使用全局变量),或使用返回值。全球方法:
x=0
.
.
def directions():
.
.
def north():
global x
x=x+1
print("moved north...")
或者,返回值:
def directions():
current_location = 0
.
.
if move == "North":
current_location = North(current_location)
.
.
def North(location):
print("moved north...")
return location+1
根据您的问题和y
的存在来判断,您可以执行以下操作:
def directions():
.
.
if move == "North":
(x,y) = North(x,y)
.
.
def North(x,y):
return (x+1,y)
def East(x,y):
return (x,y+1)
def South(x,y):
return (x-1,y)
答案 1 :(得分:1)
一些提示(不详尽,但足以开始):
首先,使用全球字典作为指示:
def north(x):
return x+1
directions = {'North': north, 'East': east, 'South': south, 'West': west}
def move(x) :
global directions
print("Type North, East, South or West to move")
move_choice = input("North, East, South or West? ")
# modify lambda to your logic to handle incorrect inputs
x = directions.get(move, lambda y:y)(x)
repr(x)
return x
如果你想要功能方法(而不是OOP),你的函数必须接受一些参数:
def north(x):
return x+1
不要混淆你的逻辑和表示,这样你就不得不复制很多代码:
def repr(x):
print("You are at co-ordinates {} x:0 y".format(x))
并将它们合并到main
例行程序中:
def main():
x = 0
while True: # modify to be able to terminate this loop
x = move(x)
答案 2 :(得分:0)
按照Cygwinnian的建议,将x
作为全局变量将解决问题。这意味着可以在使用x
之前声明global x
的所有函数访问相同的x
变量。
修复错误:
x = 0
print("Type directions() to see commands" )
def directions() :
print("Type North, East, South or West to move" )
move = input("North, East, South or West? ")
if move == "North":
north()
elif move == "East":
east()
elif move == "South":
south()
elif move == "West":
west()
def north():
global x
print("You moved North")
x=(x+1)
print("You are at co-ordinates", x, "x:0 y" )