为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法在字典的键值对中包含用户输入提示或 time.sleep() 函数?

有没有办法在字典的键值对中包含用户输入提示或 time.sleep() 函数?

MM们 2022-06-28 16:06:09
我正在开发一个 Python 文本 RPG,我正在使用字典向玩家提供有关他们正在访问的区域的初始信息。(例如参见代码)。当玩家键入“look”或“examine”时,我希望控制台打印出我在 EXAMINATION 键的值中拥有的内容。我想要它做的是一次打印一段文本,或者等待玩家在继续之前按下回车键,或者在打印下一个块之前至少等待几秒钟。有没有办法做到这一点?也许我是从错误的方向来的?import timeimport sysdef prompt():    print("\n" + "=========================")    print("What would you like to do?")    player_action = input("> ")    acceptable_actions = ['move', 'go', 'travel', 'walk', 'quit', 'examine', 'inspect', 'interact', 'look']    while player_action.lower() not in acceptable_actions:        print("Unknown action, try again.\n")        player_action = input("> ")    if player_action.lower() == 'quit':        sys.exit()    elif player_action.lower() in ['move', 'go', 'travel', 'walk']:        player_move(player_action.lower())    elif player_action.lower() in ['examine', 'inspect', 'interact', 'look']:        player_examine(player_action.lower())def player_examine(player_action):    if zonemap[myPlayer.location][SOLVED]:        print("There's nothing more here to examine.")    elif zonemap[myPlayer.location][EXAMINATION]:        slowprint(zonemap[myPlayer.location][EXAMINATION])ZONENAME = ''DESCRIPTION = 'description'EXAMINATION = 'examine'SOLVED = FalseUP = 'up', 'north'DOWN = 'down', 'south'LEFT = 'left', 'west'RIGHT = 'right', 'east'zonemap = {    'Fields': {        ZONENAME: "Western Fields",        DESCRIPTION: "A grassy field to the west of town.",        EXAMINATION: "The grass in this field is extremely soft." + input("> ") + "The wind feels cool on your face." + time.sleep(2) + "The sun is beginning to set.",        SOLVED: False,        UP: "The Mountains",        DOWN: "The Town",        LEFT: "",         RIGHT: "The Ocean",    },尝试使用 time.sleep() 方法时,出现以下错误:TypeError: can only concatenate str (not "NoneType") to str尝试使用 input("> ") 函数时,文本无需等待即可直接打印。
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

您的方法不起作用,因为您在构建字典时立即调用input()or函数。,例如,返回,这就是你得到错误的原因。time.sleep()time.sleep()None

当您从字典中检索值并且实际上想要“慢打印”描述时,您需要稍后调用这些函数。

您可以通过多种不同的方式来做到这一点。你可以

  • 使用字符串序列(例如列表或元组)而不是单个字符串,并让您的slowprint()函数接受序列并在打印每个元素后暂停。

  • 使用一系列字符串并混合特殊值来slowprint()寻找做不同的事情,比如睡觉或请求输入。

  • 在字典中存储一个函数,然后调用。函数也是对象,就像字符串一样。该函数将处理所有打印和暂停。

例如存储一个字符串元组:

EXAMINATION: (

    "The grass in this field is extremely soft.",

    "The wind feels cool on your face.",

    "The sun is beginning to set.",

)

然后让你的slowprint()函数处理:


def slowprint(lines):

    """Print each line with a pause in between"""

    for line in lines:

        print(line)

        input("> ")   # or use time.sleep(2), or some other technique

第二个选项,插入特殊值,使您能够将各种额外功能委托给其他代码。您需要测试序列中对象的类型,但这会让您在检查描述中插入任意操作。就像睡觉和要求用户击键之间的区别一样:


class ExaminationAction:

    def do_action(self):

        # the default is to do nothing

        return


class Sleep(ExaminationAction):

    def __init__(self, duration):

        self.duration = duration


    def do_action(self):

        time.sleep(self.duration)


class Prompt(ExaminationAction):

    def __init__(self, prompt):

        self.prompt = prompt


    def do_action(self):

        return input(self.prompt)

并让slowprint()函数查找这些实例:


def slowprint(examine_lines):

    for action_or_line in examine_lines:

        if isinstance(action_or_line, ExamineAction):

            # special action, execute it

            action_or_line.do_action()

        else:

            # string, print it

            print(action_or_line)

您可以进行任意数量的此类操作;关键是它们都是子类ExamineAction,因此可以与普通字符串区分开来。将它们放入您的EXAMINATION密钥序列中:


EXAMINATION: (

    "The grass in this field is extremely soft.",

    Prompt("> "),

    "The wind feels cool on your face.",

    Sleep(2),

    "The sun is beginning to set.",

)

可能性是无止境。


查看完整回答
反对 回复 2022-06-28
  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号