[英]How do I create a function that allows for user input to have a different outcomes based on how many times the same input was entered in Python?
I am creating a text based adventure game in Python. 我正在用Python创建一个基于文本的冒险游戏。 At certain points there may be rooms with many different actions you can perform, like opening a chest. 在某些时候,房间可能会执行许多不同的动作,例如打开箱子。 I want to create a single function that allows this, because right now I have to write all this: (Just an example) 我想创建一个允许该功能的函数,因为现在我必须编写所有这些代码(仅作为示例)
hello_said_once = True
hello = ["hello", "hi"]
goodbye = ["goodbye", "bye", "cya"]
while True:
user_input = raw_input("Hello... ")
if any(i in user_input for i in hello) and hello_said_once:
print "You said hello!"
elif any(i in user_input for i in hello) and not hello_said_once:
print "You already said Hello!"
elif any(i in user_input for i in goodbye) and good_bye_said_once:
print "You said Goodbye!"
break
This gets tiresome after a while and I wouldn't know how to make a function for it, specifically because the amount of actions you could perform depends on the situation. 一段时间后,这变得很烦人,我不知道如何为它创建功能,特别是因为您可以执行的操作量取决于情况。
It might be worth using a class
if you want to keep the function and usage count closely tied. 如果您想让功能和使用情况紧密联系在一起,那么使用一个class
可能是值得的。 A class can have persistent data so you could track the number of times the user called it by just increasing the number every time. 一个类可以具有持久数据,因此您可以通过每次增加该次数来跟踪用户调用它的次数。
class chest():
openCount = 0
openFunctions = [
function1,
function2,
function3,
...
]
def use(self):
self.openFunctions[openCount]
self.openCount += 1
You could use this to track other more dynamic data too, like a list of items received from chests. 您也可以使用它来跟踪其他更动态的数据,例如从箱子中收到的物品的列表。
You could probably make a class that holds a list of valid inputs and a bool for whether or not it's been triggered yet. 您可能会创建一个类,其中包含有效输入的列表以及是否已被触发的布尔值。
class Action:
def __init__(self, user_inputs):
self.user_inputs = user_inputs
self.been_triggered = False
hello = Action(["hello", "hi"])
goodbye = Action(["goodbye", "bye", "cya"])
Also, your use of "any" is redundant. 另外,您对“ any”的使用是多余的。 You can just say if user_input in hello and ...
您可以只说if user_input in hello and ...
class Action:
def __init__(self, user_inputs):
self.user_inputs = user_inputs
self.been_triggered = False
hello = Action(["hello", "hi"])
goodbye = Action(["goodbye", "bye", "cya"])
while True:
user_input = raw_input("Hello... ")
if user_input in hello.user_inputs:
if not hello.been_triggered:
print "You said hello!"
else:
print "You already said Hello!"
elif user_input in goodbye.user_inputs:
print "You said Goodbye!"
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.