如何再次使用命令而不复制和粘贴它们?

时间:2013-09-01 10:43:38

标签: python

我真的不知道怎么解释这个......但是我正在为学习基础知识做文本冒险。现在我想制作一个黄金和金钱系统,我正在使用def ...不同级别的东西等等。但是如果用户键入黄金,我必须输入每个提示,或者它显示库存然后返回到def所在的位置..我每次都觉得很烦人。在某些时期我也会忘记它。我想在提示中将其作为默认值。 我有一个def提示符():就是这个简单的代码:

def prompt():
    x = input('Type a command: ')
    return x

如果我把它放在那里它只是结束代码。我必须在每个提示中都这样做:

def AlleenThuis():
    command = prompt()
    if command == '1':
        print()
    elif command == '2':
        print()
    elif command == '3':
        print()
    elif command == '4':
        print()
    elif command == 'geld': #Actions start here
        print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
        print()
        return AlleenThuis()
    elif command == 'inv':
        if not inv:
            print("\n\tYou don't have any items..\n")
            return AlleenThuis()
        else:               #The else has to stay in this place because it's part of the 'if not inv:' guys.
            print('\n\t' + str(inv) + '\n')
            return AlleenThuis()
            #Actions end here

所以如果有任何方法可以实现它,那么每次我都不需要再次使用它! 感谢。

编辑:看起来你们不理解我在说什么,所以我有2张图片。 所以.. http://i.imgur.com/GLArsyu.png (我无法发布图片= [)

正如你在这张照片中看到的,我已经包含了黄金和inv。 但是在 http://i.imgur.com/V3ZhJ36.png 中我也做到了,所以我再次在代码中编码,这就是我不想要的!

我只想在代码中获得一次,并且让玩家为他们输入命令时让黄金和库存一直显示!

6 个答案:

答案 0 :(得分:1)

您的代码有一些严重的结构问题。如果我理解正确,你会尝试接受重复的命令并执行一些代码,使它们按照你想要的方式运行。

问题在于你运行游戏的功能是递归的,因此每次执行除1,2,3或4之外的命令时,你都会再次调用你的函数,而不会从第一个函数返回。最后,如果你输入足够的命令,你会收到一个错误,说你的复制太深,游戏就会出错。

你想要的是更像这样的东西:

def prompt():
    x = input('Type a command: ')
    return x

def ProcessAction(command):
    if command == '1':
        print()
    elif command == '2':
        print()
    elif command == '3':
        print()
    elif command == '4':
        print()
    elif command == 'geld': #Actions start here
        print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
        print()
    elif command == 'inv':
        if not inv:
            print("\n\tYou don't have any items..\n")
    else:
        print('\n\t' + str(inv) + '\n')
    #Actions end here

curr_command = None
while curr_command not in ("1", "2", "3", "4"):
    curr_command = prompt()
    ProcessAction(curr_command)

这样做的目的是不断询问新命令并处理它们,直到输入退出游戏的其中一个命令为止。

编辑:从下面的评论中,听起来您正试图弄清楚每次输入命令时如何显示黄金和库存,而无需执行特殊命令。如果这是您所追求的,您可以将打印语句添加到上面的while循环,以确保在每个提示之前打印它。在这种情况下,while循环可能如下所示:

while curr_command not in ("1", "2", "3", "4"):
    print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
    if not inv:
        print("\n\tYou don't have any items..\n")
    else:
        print('\n\t' + str(inv) + '\n')
    curr_command = prompt()
    ProcessAction(curr_command)

希望接近你所追求的目标。

编辑2:好的,在阅读了游戏的完整代码之后,我想你可能会考虑重组整个事情。想想你想要的游戏:玩家输入一系列命令,每个命令做两件事,它改变了游戏的状态,并根据当前状态和新状态打印出响应。

所以,您应该考虑使用我所描述的循环来处理您的命令。然后,将所有这些不同的函数折叠成一个ProcessAction(command)函数,该函数从游戏的状态(存储在变量中)中计算出要打印的内容以及如何更改状态。

例如,如果这是一个你要进入房间的游戏,你可以保留一个全局变量room来定义你的位置。然后你的ProcessAction函数遵循逻辑,即“如果我在房间A中并且字符类型这个东西然后打印出B并将空间更改为C,并将黄金设置为0。”

为了使这项工作做得好,你将不得不退后一步思考游戏的整体“故事”,如何将状态存储在各种变量中,以及如何使你的ONE ProcessAction函数处理所有可能发布的状态和命令。

这样做会让你走上开发所谓的“状态机”的道路,你可以在这里找到一个简单的通用函数来查看数据结构(可能是一些嵌套的dicts),这些函数填充了每个命令的作用。你的游戏在每个州和下一个地方,以及打印的内容。

这篇维基百科文章描述了状态机的概念。如何在Python中实现它取决于您。我可以告诉你,如果你小心,你应该能够做到这一点而不重复任何代码。 http://en.wikipedia.org/wiki/State_machine

另一个编辑:回答你在下面的评论中提出的问题,如果你认为你必须打印出来,例如,玩家的黄金在多个地方的价值,你可以这样做:

def print_gold(gold_value):
    print('\n\tYou have ' + str(gold_value) + ' euro. RICH BOY BRO!.\n')
    print()

然后在需要时使用print_gold(gold)代替那些print语句。但是,我认为你可能想退后一步,考虑在解决这个问题之前用我提出的一些想法重写整个事情。

答案 1 :(得分:1)

我之前的答案很长,并解决了OP代码中的一些问题,但他问的是一个具体的问题,所以我想我会在这里找出答案。

如果您有一些代码需要重复多次,那么您可能很想在代码中复制并粘贴它。在您的情况下,这将是:

print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
print()

在函数中包装它将允许您在需要执行该操作时执行相同的代码,而无需复制和粘贴。你已经定义了函数,所以你似乎有了概念,但这包含在一个函数中可能看起来像:

def print_gold(gold_value):
    print('\n\tYou have ' + str(gold_value) + ' euro. RICH BOY BRO!.\n')
    print()

定义此函数后,只要您在代码中放置print_gold(gold),它就会将gold的值作为变量gold_value传递给该函数并将其打印出来。已指定。

因此,如果出于某种原因,您的代码看起来像这样:

print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
print()
print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
print()
print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
print()

你可以把它变成:

def print_gold(gold_value):
    print('\n\tYou have ' + str(gold_value) + ' euro. RICH BOY BRO!.\n')
    print()

...  somewhere else in your code ...

print_gold(gold)
print_gold(gold)
print_gold(gold)

这三行是​​函数调用,它告诉Python执行你用def定义的函数。

答案 2 :(得分:1)

在更基础的层面上,面向对象的范例优雅地解决了重复代码的问题:

global gold = 0
def cave():
    print "You are in a cave."
    print "You have %i gold." % gold
    direction = input()
    if direction = 'N':
        stream()
    elif direction == 'S':
        house()
    elif direction == 'W':
        mountain()
    elif direction == 'directions':
        print "You can go North, West, or South."
    else:
        print "You cannot go there."
def stream():
    print "A small stream flows out of the building and down a gully."
    print "You have %i gold." % gold
    direction = input()
    if direction == 'N':
        tree()
    elif direction == 'S':
        cave()
    elif direction == 'directions':
        print "You can go North or South."
    else:
        print "You cannot go there."

def main():
    cave()

把它变成这样的东西:

class Location:
    map = { 'cave': {
              'description': 'You are in a cave.',
              'directions': { 'N': 'stream', 'S': 'house', 'W': 'mountain' } },
            'stream': {
              'description':
                'A small stream flows out the building and down a gully.',
              'directions': { 'N': 'tree', 'S': 'cave' } } #...
          }
    def __init__ (self):
        self.location = 'cave'
    def enter (self, direction):
        self.location = self.map[self.location]["directions"][direction]
        print self.map[self.location]["description"]
    def directions(self):
        return self.map[self.location]["directions"].keys()
    def readable(self, dirs):
        readable = { 'S': 'South', 'N': 'North', 'W': 'West', 'E': 'East' }
        return [readable[d] for d in dirs]

class Inventory:
    def __init__ (self):
        self.inventory = { 'gold': 0 }
    def query (self):
        print "You have %i gold." % self.inventory['gold']

def main:
    loc = Location()
    inv = Inventory()
    while True:
        directions = loc.directions()
        action = raw_input()
        if action in directions:
            loc.enter(action)
            inv.query()
        elif action == 'directions':
            where = loc.readable(directions)
            print "You can go " + ", ".join(where[:-1])\
                  + ", or " + where[-1]
        else:
            print "You cannot go there."

您会注意到更模块化的代码也更容易扩展。例如,库存现在可以容纳比黄金更多的东西,并且很容易添加新命令来查询武器,药水等。此外,它有点将代码与数据分开,使其不那么麻烦且容易出错。新的地点和行动。

接下来,为动画对象,可以拾取的对象,不动对象等定义class Object子类;并使用这些实例填充位置。不同的子类可以定义不同的交互,并从更基本的超类继承,这些超类实现了takedropkill等基础知识。

映射到对象的内容是一个广泛的主题,但是一些简单的指导原则是将不相关的代码隔离并封装到它们自己的类中,并使它们尽可能地分离(实现“位置”的代码应该不需要知道关于“库存”中的代码,反之亦然。

答案 3 :(得分:0)

如果我正确理解了您问题的最新修改,那么您可能需要以下内容:

def get_gold_or_inv(command):
        if command == 'geld': #Actions start here
            print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
            print()
        elif command == 'inv':
            if not inv:
                print("\n\tYou don't have any items..\n")
            else:
                print('\n\t' + str(inv) + '\n')

while True:
    command = prompt()
    if command == '1':
        print()
    elif command == '2':
        print()
    elif command == '3':
        print()
    elif command == '4':
        print()
    get_gold_or_inv(command)

答案 4 :(得分:0)

你是否想说你想让它在无限循环中运行直到退出? 您可以通过使用while True:封装整个功能块或仅在ifelif之后调用AlleenThuis()来实现此目的。我冒昧地使用下面的第一个选项重写你的实现。

def AlleenThuis():
    while True:
        command = prompt()
        if command == '1':
            print()
        elif command == '2':
            print()
        elif command == '3':
            print()
        elif command == '4':
            print()
        elif command == 'geld': #Actions start here
            print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
            print()
        elif command == 'inv':
            if not inv:
                print("\n\tYou don't have any items..\n")
            else:
                print('\n\t' + str(inv) + '\n')
        else:
            print("Invalid command")

希望我没有误会你。

修改

def action(cmd):
    if cmd == 'geld':
        print('\n\tYou have ' + str(gold) + ' euro. RICH BOY BRO!.\n')
        print()
    elif cmd == 'inv':
        if not inv:
            print("\n\tYou don't have any items..\n")
        else:
            print('\n\t' + str(inv) + '\n')
    else:
        # If the command was not found
        return False
    # If the command was found and the else statement was not run.
    return True

然后在每个方案if action(command): return ScenarioName()开始时运行它。 希望有所帮助!

答案 5 :(得分:0)

我假设您每次想要运行Python程序时都会在此提示符中粘贴一些内容,而您的问题是如何避免这种情况:

enter image description here

这个问题的答案通常是将程序的代码保存在whatever.py文件中,并通过双击或通过终端运行该文件。具体说明取决于您的操作系统等。