亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法在字典的鍵值對中包含用戶輸入提示或 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 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號