我对Python很陌生,我正在尝试制作一个冒险游戏,只是为了培养我的技能。所以,对于我的游戏,我希望有一些选项,玩家将选择一个,它将返回不同的结果。但是,选项并不总是相同,所以我决定创建一个函数,因此选项和结果可能会有所不同。这是我的函数的代码:
def action(act1, act2, act3, act4):
loop = True
while loop:
print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
act1
return
elif player_action == '2':
act2
return
elif player_action == '3':
act3
return
elif player_action == '4':
act4
return
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
参数是我要打印的功能。
我的问题是,当我调用此函数并运行代码时,Python会在每个if和elif语句中执行每个函数。例如,当我这样称呼时:
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
action(home_act1(), home_act2(), home_act3(), home_act4())
我运行程序并执行此操作: 欢迎来到荒野! 欢迎来到小镇! 欢迎光临本店! 你离开了冒险。
处理完成,退出代码为0
它似乎只是运行我的所有四个参数,它在我使它成为一个函数之前有效,但有些东西不能正常工作。
感谢您的帮助!
答案 0 :(得分:0)
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
def action():
loop = True
while loop:
# print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
return home_act1() #or you can remove the return and carry on in the function
elif player_action == '2':
return home_act2()
elif player_action == '3':
return home_act3()
elif player_action == '4':
return home_act4()
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
action()
您可以返回函数调用:
def functionToCall():
print('Ok function called')
def function():
return functionToCall()
function()
答案 1 :(得分:0)
您拥有所有4个输出然后退出代码的原因是因为您通过执行home_act
立即调用所有四个action(home_act1(), home_act2(), home_act3(), home_act4())
函数,exit()
一个接一个地执行并且由于{{而退出程序1}} home_act4()
。
另一个有问题的是你在while循环中的每个动作之后return
,这意味着一旦用户完成一个动作,代码就会停止。
修复这些问题会产生以下代码:
def action():
loop = True
while loop:
#print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
home_act1() # call the respective action function here
elif player_action == '2':
home_act2()
elif player_action == '3':
home_act3()
elif player_action == '4':
home_act4()
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
action()
祝你好运,进一步编码:)
答案 2 :(得分:0)
在这一行:
action(home_act1(), home_act2(), home_act3(), home_act4())
您实际上正在调用每个函数并传递结果(None
在每种情况下,因为这是默认值。
尝试仅传递函数(home_act
而不是home_act()
),然后在循环体中实际调用act()
。