如何仅禁用一件事(来自用户输入)并保持其他 运行 30 秒?

How to disable only one thing (from user input) and keep the others running for 30 seconds?

假设您正在制作一款游戏,它有一个输入询问您想要做什么。

 bal=0
while True:
  question=input("What do you want to do?")
    if(input=="beg"):
      print(Adding 500$ to your balance.)
      bal=bal+500
    elif(input=="bal"):
      print("Balance: "+str(bal))

我想制作一个计时器,这样用户在 30 秒内不能使用 beg 命令。但仍然可以使用其他命令——我可能会添加更多命令。 顺便说一句,我不能在这里缩进网站页面向下但想象一下 while true 循环和 ifs 有正确的缩进。

你可以借助时间模块来完成。

import time
bal=0
start = 0
while True:
  question=input("What do you want to do?")
    if(question=="beg"):
      if(time.time()-start>=30):
          print(Adding 500$ to your balance.)
          bal=bal+500
          start = time.time()
      else:
          print("Wait for",30-time.time()+start,"seconds")
    elif(question=="bal"):
      print("Balance: "+str(bal))
      time.sleep(5)

一种方法,一个上次使用的字典(正如你提到的,你会有更多)

from time import time

def beg():
    # your code

commands = {
    "beg": {"func": beg, "last_time":0, "timeout": 30 }, #maybe more stuff
    "another": {"func": another, "last_time":0, "timeout": 10 },
    # ...
} # you are likely wanting to build this dict dynamically, maybe

while True:
    question = input("What do you want to do?")
    if question in commands:
        if time() > commands[question]["last_time"] + commands[question]["timeout"]:
            commands[question]["func"]() # this executes the function of the command
            commands[question]["last_time"] = time() # this sets the time as of now
        else: print(f"you are not allowed to use {question} yet") # you get the idea
    else: print("command not recognized") # yada