我是一个非常新的初学者编码,我不知道很多。我正在尝试创建一个猜谜游戏,我想在程序中添加一个计时器。 计时器的工作方式是,我设置一个设定的时间量,即60秒,一旦时间用完,程序就会停止,基本上就像“对不起,时间用完了。你想再试一次吗?”
我已经在YouTube和Stackoverflow上搜索了一些视频,但我要么不懂,要么就是做不到
https://www.youtube.com/watch?v=Mp6YMt8MSAU
这段视频我已经看了4遍了,但仍然不知道该怎么做。因此,如果有人愿意向我解释/告诉我如何增加时间,我将不胜感激
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: " ))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances, it is now player 2's turn to play. The number was", n)
break
if guess < n:
print("guess is low you have",chances,"chances left")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high you have",chances, "chances left")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances, "chances left")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances, the number was", n1)
break
if guess1 < n1:
print("guess is low you have",chances1,"chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high you have",chances1, "chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances1, "chances left")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
if retry == "yes":
main()
elif retry == "no":
print("Okay. have a nice day! :D ")
else:
print("Invalid input")
main()
这是我的密码。如有任何反馈,将不胜感激
(我不知道您对python和编程了解多少,所以我将使用一种非常简单的语言)
好吧,如果你的游戏不需要在计时器处于活动状态时运行,你可以使用时间库的睡眠功能,并写下如下内容:
使用“command”time.sleep,python将在您选择的时间内停止整个程序
(因此,如果必须在计时器运行时玩游戏,请不要使用time.sleep方法)
相反,如果在玩游戏时计时器必须处于活动状态,则应使用“线程”。 线程是一个库,它允许您执行非常简单的计时器,但不仅仅是。 用线程制作计时器对你来说可能更复杂,但不是真的
您必须编写一个函数,以便在计时器结束时调用,如下所示:
之后,您必须创建计时器:
最后,您必须开始计时器写入:
这样,python将: 1-导入线程库 2-创建您想要的时间量的计时器 3-启动计时器 4-在时间用完时激活您编写的功能
如果你需要关于其中一种方法的更多信息,请写一条评论,我会尽快回答你的问题
祝您愉快:)
要解决您的问题,您必须使用
Thread
。我拿了你的代码,我在开头添加了线程,试着看一看线程是可以在主程序旁边执行函数(其
run
函数)的对象。这就是所谓的并行编程这里您需要它,因为您想要:
我没有修改你的代码或重写它,我只是添加了线程并使其工作。这很简单:
sleep
(_TIME_LIMIT
]True
,这意味着计时器结束只要稍加重写,当线程更改变量时,您就可以中断主循环。但这超出了最初问题的范围,请随意改进您的游戏。
目前,您需要输入一个数字来知道时间是否结束。这就是为什么我添加了小噪音(如果没有,您将没有提示)
请随时提问。
希望这对你有帮助
相关问题 更多 >
编程相关推荐