0

我真的不知道如何准确地解释这一点。但我正在为学习基础知识进行文字冒险。现在我想制作一个黄金和货币系统,我正在使用 def... 不同级别的东西等等。但是,如果用户键入黄金,我必须在每个提示中输入,或者 inv 它显示库存,然后返回到它所在的 def.. 我每次都觉得这样做很烦人。我有时也会忘记它。我想在提示中默认这样做。我有一个 def prompt(): 就是这个简单的代码:

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(我还不能发布图片=[)

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

我只想在代码 1 中使用它,并在玩家为他们输入命令时让金币和库存一直显示!

4

6 回答 6

2

在更基本的层面上,面向对象的范式优雅地解决了重复代码的问题,如下所示:

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为动画对象、可以拾取的对象、固定对象等定义子类;并用这些实例填充位置。不同的子类可以定义不同的交互,并从更基本的超类继承,这些超类实现了take, drop,kill等基本原理。

将什么映射到对象是一个广泛的话题,但一些简单的指导方针是将不相关的代码隔离并封装到它们自己的类中,并使它们尽可能地解耦(实现“位置”的代码不需要知道任何关于“库存”中的代码,反之亦然)。

于 2013-09-01T16:39:49.330 回答
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。”

为了使这项工作顺利进行,您必须退后一步考虑游戏的整体“故事”,如何将状态存储在各种变量中,以及如何让您的 ONEProcessAction函数处理所有可能的状态和命令发行。

这样做会让你走上开发所谓的“状态机”的道路,在那里你有一个简单的通用函数,它查看一个数据结构(可能是一些嵌套的 dicts),当你的游戏运行时,你可以填充每个命令的作用在每个州,下一步要去哪里,以及要打印什么。

这篇 Wikipedia 文章描述了状态机的概念。如何在 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)在需要时使用代替那些打印语句。但是,我认为您可能想退后一步,考虑在解决该问题之前用我提供的一些想法重写整个内容。

于 2013-09-01T10:59:50.193 回答
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.

于 2013-09-01T11:44:57.293 回答
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)
于 2013-09-01T10:57:40.760 回答
0

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

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()。希望有帮助!

于 2013-09-01T11:01:30.107 回答
0

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

在此处输入图像描述

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

于 2013-09-01T11:11:27.310 回答