python - 一旦玩家达到 Python 游戏的设定时间,如何停止程序

标签 python python-3.x pygame

我刚刚接触 Python,正在尝试创建一个问答游戏。我想在我的测验中添加一个 2 分钟的倒计时计时器,这样当计时器达到零时,问题就会停止并说你没时间了。我也尝试用秒表来做到这一点,但无法弄清楚如何终止比赛,所以如果你知道如何做到这一点,那就同样好。

注意:我没有使用 pygame。许多其他用户在之前的主题中提出过问题。

这是我从其他文档中收集的代码,但它不会在达到 2 分钟或 0 分钟后停止。

def countdown():
    t = 60
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    print("You're out of time!\n")
    sys.exit ("goodbye")

def main_game():
    count_thread = threading.Thread(None, countdown)
    question_4 = ("question 1?")
    option_4 = (" a. 1 \n b. 5 \n c. 3 \n d. 7")
    print(question_4)
    print(option_4)            
    answer_4 = input (">")
    if answer_4.lower()== "b":
        score = score + 100
    else:
        print("Incorrect")
import time
start1 = time.time()
if start1 >= 120:
      import sys
      sys.exit
question_a = ("question?")
option_a = (" a. 7 \n b. 8 \n c. 2 \n d. 1")
print(question_a)
print(option_a)            
answer_a = input (">")
if answer_a.lower()== "b":
     score = score + 100
else:
    print("Incorrect")
###rest of questions

end1 = time.time()

两个代码都是我试过的两个不同版本。这两个代码都不起作用。底部代码为播放计时,但它不会在 2 分钟标记处停止。

如有任何帮助、建议或反馈,我们将不胜感激!

最佳答案

由于您使用 Pygame .

simplest code您可能应该(按照良好的编码标准)包括 pygame.quit()。像这样:

import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
               pygame.quit()
               sys.exit()
               pygame.display.update()

紧随其后的是 Python sys.exit功能。

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

您可以在不显式使用 Python 线程的情况下制作问答游戏,但如果您打算使用 Python 线程,则可以从查看 here 中的快速示例开始。 .

希望这对您有所帮助。您已经可以在线找到 pygame 中的测验,并可能对其进行修改。

关于python - 一旦玩家达到 Python 游戏的设定时间,如何停止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56272479/

相关文章:

python - 在 Python 中将 16 个字节的随机数据转换为整数

python - 给定一个值列表,删除第一次出现的

python - 根据集合中的存在将条目添加到 pandas 数据框

python - 如何将行字符串值转换为特征

python - Pygame 错误未显示缩放图像

python-3.x - python - add() 不会将类的实例添加到组中,因为它不可迭代,但它正在迭代

python - pygame clock.tick() vs 游戏主循环中的帧率

python - 全屏 matplotlib 数字

python - pandas如何在不创建新列的情况下进行外连接

python - 如何从 Python 脚本调用 clang-format