如何让文字显示5秒然后消失并显示按钮?

2024-04-30

我正在努力做到这一点,以便当您在我的问答游戏中得到正确答案时,它会摆脱您看到的大问题并说“干得好”5秒钟,然后返回到主菜单,其中随机有4个选定的问题。问题从 quizfile.csv 加载并包含:

What colour is elon musk's hair?,brown
What is most popular sport?,football
What was Queen first called?,Smile
What's superior Apple Or Windows?,Windows

它们是随机的,因为它们只是占位符并且仅用于测试目的。 我想要暂停/显示5秒功能的地方是第一个文件的第115行。

我努力了time.sleep(5)这只会冻结程序并且在 5 秒内不显示它,就像不到一秒一样。我需要使用吗pygame.event.set_timer()如果是这样,怎么办?

import csv
import sys
import random
import pygame
import textwrap
import time
import pygame_textinput
textinput = pygame_textinput.TextInput()


pygame.init()
clock = pygame.time.Clock()
FPS=60
SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1080, 720
screen = pygame.display.set_mode(SCREENSIZE)

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)
green = (0, 255, 0)

questions = {}

def wrap_text(message, wraplimit): #keep text on screen
    return textwrap.fill(message, wraplimit)

def text_objects(text,font): #render text
    textSurf = font.render(text, True, black)
    return textSurf, textSurf.get_rect()


def question(text):
    xx=0
    text = wrap_text(text,20) #wrap text
    largeText = pygame.font.Font('freesansbold.ttf',100)
    for part in text.split('\n'): #for each line from the wrapped text
        TextSurf, TextRect = text_objects(part, largeText)
        TextRect.center = ((SCREENWIDTH/2)),(SCREENHEIGHT/2+xx)
        screen.blit(TextSurf, TextRect)
        xx+=75 #change height of text so doesnt overlap



class Button:
    def __init__(self, question, answer,positionx,positiony): #setup all vars
        self.question = question
        self.answer = answer
        self.positionx = positionx
        self.positiony = positiony

    def button(self):
        ltr = len(self.question)
        w= 12.5*ltr #make width of button big enough for text
        button = pygame.Rect(self.positionx,self.positiony,w,50) #make button
        largeText = pygame.font.Font('freesansbold.ttf',20)
        TextSurf, TextRect = text_objects(self.question, largeText)
        TextRect.center = ((self.positionx+(w/2)),(self.positiony+25)) #button text
        return button, TextSurf, TextRect
    def question(self):
        question(self.question) #display question
    def giveQuestionAnswer(self):
        return self.question,self.answer #give question and answer

with open("quizfile.csv") as f: #load in questions
    reader = csv.reader(f)
    quiz_qas = list(reader) 

z=0 #for positioning
t=0 #for loop
quiz = random.sample(quiz_qas, 4) #randomly select 4 questions
for q, a in quiz: #for every question and answer in the file
    questions[q] = a #define the dictionary of questions and answers
    for x, y in questions.items(): #for every answer and question in the dictionary, link them
        if t==0: #the sweet spots for getting a different question every time
            b = Button(x,y,200,200) #make button object
            z+=50

        elif t==5:
            b1 = Button(x,y,600,200)
            z+=50

        elif t==7:
            b2 = Button(x,y,600,400)
            z+=50
        elif t==9:
            b3 = Button(x,y,200,400)
            z+=50
        t+=1

b2on = False #for handling displaying the question
b3on = False
b4on = False
b5on = False
correct=False
gameState = "running"  # controls which state the games is in
# game loop #################### runs 60 times a second!
while gameState != "exit":  # game loop - note:  everything in the mainloop is indented one tab

    screen.fill(white)
    events = pygame.event.get()
    if b2on:
        q,a = b.giveQuestionAnswer() #get question and answer
        question(q) #display answer
        # Feed it with events every frame
        # Blit its surface onto the screen
        screen.blit(textinput.get_surface(), (10, 10))
        if textinput.update(events): #if hit enter
            if textinput.get_text() == a:
                b2on = False
                correct=True

    if correct:
        question("well done")
        #PAUSE SCREEN HERE AND DISPLAY WELL DONE FOR 5 SECONDS
        correct=False

    elif b3on:
        q,a = b1.giveQuestionAnswer()
        question(q)

        textinput.update(events)
        screen.blit(textinput.get_surface(), (10, 10))
        if textinput.update(events): #if hit enter
            if textinput.get_text() == a:
                b3on = False
                correct=True

    elif b4on:
        q,a = b2.giveQuestionAnswer()
        question(q)

        textinput.update(events)
        screen.blit(textinput.get_surface(), (10, 10))
        if textinput.update(events): #if hit enter
            if textinput.get_text() == a:
                b4on = False
                correct=True

    elif b5on:
        q,a = b3.giveQuestionAnswer()
        question(q)

        textinput.update(events)
        screen.blit(textinput.get_surface(), (10, 10))
        if textinput.update(events): #if hit enter
            if textinput.get_text() == a:
                b5on = False
                correct=True

    elif b2on==False and b3on==False and b4on==False and b5on==False:
        B2,TextSurf,TextRect = b.button() #draw buttons
        pygame.draw.rect(screen, [255, 0, 0], B2)
        screen.blit(TextSurf, TextRect)

        B3,TextSurf,TextRect = b1.button()
        pygame.draw.rect(screen, [255, 0, 0], B3)
        screen.blit(TextSurf, TextRect)

        B4,TextSurf,TextRect = b2.button()
        pygame.draw.rect(screen, [255, 0, 0], B4)
        screen.blit(TextSurf, TextRect)

        B5,TextSurf,TextRect = b3.button()
        pygame.draw.rect(screen, [255, 0, 0], B5)
        screen.blit(TextSurf, TextRect)


    for event in pygame.event.get():  # get user interaction events
        if event.type == pygame.QUIT:  # tests if window's X (close) has been clicked
            gameState = "exit"  # causes exit of game loop
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos  # gets mouse position

            if B2.collidepoint(mouse_pos): #if click on button
                b2on = True #display question
            if B3.collidepoint(mouse_pos):
                b3on = True
            if B4.collidepoint(mouse_pos):
                b4on = True
            if B5.collidepoint(mouse_pos):
                b5on = True


    pygame.display.update()            
    pygame.display.flip()  # transfers build screen to human visable screen
    clock.tick(FPS)  # limits game to frame per second, FPS value

# out of game loop ###############
print("The game has closed") 
pygame.quit() 
sys.exit()  

这是我用来创建闪烁输入效果和功能的 pygame_textinput.py 文件。

"""
Copyright 2017, Silas Gyger, [email protected] /cdn-cgi/l/email-protection, All rights reserved.

Borrowed from https://github.com/Nearoo/pygame-text-input under the MIT license.
"""

import os.path

import pygame
import pygame.locals as pl

pygame.font.init()


class TextInput:
    """
    This class lets the user input a piece of text, e.g. a name or a message.
    This class let's the user input a short, one-lines piece of text at a blinking cursor
    that can be moved using the arrow-keys. Delete, home and end work as well.
    """
    def __init__(
            self,
            initial_string="",
            font_family="",
            font_size=35,
            antialias=True,
            text_color=(0, 0, 0),
            cursor_color=(0, 0, 1),
            repeat_keys_initial_ms=400,
            repeat_keys_interval_ms=35):
        """
        :param initial_string: Initial text to be displayed
        :param font_family: name or list of names for font (see pygame.font.match_font for precise format)
        :param font_size:  Size of font in pixels
        :param antialias: Determines if antialias is applied to font (uses more processing power)
        :param text_color: Color of text (duh)
        :param cursor_color: Color of cursor
        :param repeat_keys_initial_ms: Time in ms before keys are repeated when held
        :param repeat_keys_interval_ms: Interval between key press repetition when helpd
        """

        # Text related vars:
        self.antialias = antialias
        self.text_color = text_color
        self.font_size = font_size
        self.input_string = initial_string  # Inputted text

        if not os.path.isfile(font_family):
            font_family = pygame.font.match_font(font_family)

        self.font_object = pygame.font.Font(font_family, font_size)

        # Text-surface will be created during the first update call:
        self.surface = pygame.Surface((1, 1))
        self.surface.set_alpha(0)

        # Vars to make keydowns repeat after user pressed a key for some time:
        self.keyrepeat_counters = {}  # {event.key: (counter_int, event.unicode)} (look for "***")
        self.keyrepeat_intial_interval_ms = repeat_keys_initial_ms
        self.keyrepeat_interval_ms = repeat_keys_interval_ms

        # Things cursor:
        self.cursor_surface = pygame.Surface((int(self.font_size/20+1), self.font_size))
        self.cursor_surface.fill(cursor_color)
        self.cursor_position = len(initial_string)  # Inside text
        self.cursor_visible = True  # Switches every self.cursor_switch_ms ms
        self.cursor_switch_ms = 500  # /|\
        self.cursor_ms_counter = 0

        self.clock = pygame.time.Clock()

    def update(self, events):
        for event in events:
            if event.type == pygame.KEYDOWN:
                self.cursor_visible = True  # So the user sees where he writes

                # If none exist, create counter for that key:
                if event.key not in self.keyrepeat_counters:
                    self.keyrepeat_counters[event.key] = [0, event.unicode]

                if event.key == pl.K_BACKSPACE:
                    self.input_string = (
                        self.input_string[:max(self.cursor_position - 1, 0)]
                        + self.input_string[self.cursor_position:]
                    )

                    # Subtract one from cursor_pos, but do not go below zero:
                    self.cursor_position = max(self.cursor_position - 1, 0)
                elif event.key == pl.K_DELETE:
                    self.input_string = (
                        self.input_string[:self.cursor_position]
                        + self.input_string[self.cursor_position + 1:]
                    )

                elif event.key == pl.K_RETURN:
                    return True

                elif event.key == pl.K_RIGHT:
                    # Add one to cursor_pos, but do not exceed len(input_string)
                    self.cursor_position = min(self.cursor_position + 1, len(self.input_string))

                elif event.key == pl.K_LEFT:
                    # Subtract one from cursor_pos, but do not go below zero:
                    self.cursor_position = max(self.cursor_position - 1, 0)

                elif event.key == pl.K_END:
                    self.cursor_position = len(self.input_string)

                elif event.key == pl.K_HOME:
                    self.cursor_position = 0

                else:
                    # If no special key is pressed, add unicode of key to input_string
                    self.input_string = (
                        self.input_string[:self.cursor_position]
                        + event.unicode
                        + self.input_string[self.cursor_position:]
                    )
                    self.cursor_position += len(event.unicode)  # Some are empty, e.g. K_UP

            elif event.type == pl.KEYUP:
                # *** Because KEYUP doesn't include event.unicode, this dict is stored in such a weird way
                if event.key in self.keyrepeat_counters:
                    del self.keyrepeat_counters[event.key]

        # Update key counters:
        for key in self.keyrepeat_counters:
            self.keyrepeat_counters[key][0] += self.clock.get_time()  # Update clock

            # Generate new key events if enough time has passed:
            if self.keyrepeat_counters[key][0] >= self.keyrepeat_intial_interval_ms:
                self.keyrepeat_counters[key][0] = (
                    self.keyrepeat_intial_interval_ms
                    - self.keyrepeat_interval_ms
                )

                event_key, event_unicode = key, self.keyrepeat_counters[key][1]
                pygame.event.post(pygame.event.Event(pl.KEYDOWN, key=event_key, unicode=event_unicode))

        # Re-render text surface:
        self.surface = self.font_object.render(self.input_string, self.antialias, self.text_color)

        # Update self.cursor_visible
        self.cursor_ms_counter += self.clock.get_time()
        if self.cursor_ms_counter >= self.cursor_switch_ms:
            self.cursor_ms_counter %= self.cursor_switch_ms
            self.cursor_visible = not self.cursor_visible

        if self.cursor_visible:
            cursor_y_pos = self.font_object.size(self.input_string[:self.cursor_position])[0]
            # Without this, the cursor is invisible when self.cursor_position > 0:
            if self.cursor_position > 0:
                cursor_y_pos -= self.cursor_surface.get_width()
            self.surface.blit(self.cursor_surface, (cursor_y_pos, 0))

        self.clock.tick()
        return False

    def get_surface(self):
        return self.surface

    def get_text(self):
        return self.input_string

    def get_cursor_position(self):
        return self.cursor_position

    def set_text_color(self, color):
        self.text_color = color

    def set_cursor_color(self, color):
        self.cursor_surface.fill(color)

    def clear_text(self):
        self.input_string = ""
        self.cursor_position = 0

任何帮助表示赞赏!


您必须使用计时器事件。看pygame.event https://www.pygame.org/docs/ref/event.html.

创建一个用户事件和paused state.

pausetimerevent = pygame.USEREVENT + 1
paused = False

如果游戏暂停则显示“做得好”。当答案正确后,再设置paused = True并启动计时器。看pygame.time.set_timer https://www.pygame.org/docs/ref/time.html#pygame.time.set_timer:

while gameState != "exit": 

    if not paused and b2on:
        # [...]


    if paused:
        question("well done")

    elif correct:
        correct = False
        paused = True
        pygame.time.set_timer(pausetimerevent, 5000) # 5000 milliseconds = 5 socond 

时间过去后,事件发生。重置paused并通过将 0 传递给时间参数来重置计时器:

while gameState != "exit": 

    # [...]

    for event in pygame.event.get():  # get user interaction events
        if event.type == pygame.QUIT:  # tests if window's X (close) has been clicked
            gameState = "exit"  # causes exit of game loop
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos  # gets mouse position

            # [...]

        if event.type == pausetimerevent:
            pygame.time.set_timer(pausetimerevent, 0) # stop timer
            paused = False
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让文字显示5秒然后消失并显示按钮? 的相关文章

随机推荐

  • Python:从自定义域发送电子邮件

    我正在尝试从 Python 中的自定义域发送电子邮件 我已经弄清楚如何使用 smtplib 从其他域 例如 gmail com 发送电子邮件 示例代码 https stackoverflow com questions 57842922 c
  • 我们可以从 MFCC 系数中恢复音频吗?

    可以从 MFCC 系数中获取音频信号吗 另外 MFCC 系数是否有一个值范围 如果有的话 是什么 如果没有 如何将其归一化在 0 到 1 之间 我尝试使用以下 MATLAB 代码 http labrosa ee columbia edu m
  • 如何在代码中使用毕加索设置背景图像

    我知道毕加索将图像加载到 imageview 等中 但如何使用毕加索设置布局背景图像 My code public class MainActivity extends ActionBarActivity Override protecte
  • 在 dplyr::filter 中传递字符串作为变量名

    我使用 mtcars 数据集来说明我的问题 例如 我想将数据子集到 4 缸汽车 我可以这样做 mtcars gt filter cyl 4 在我的工作中 我需要传递一个字符串变量作为我的列名 例如 var lt cyl mtcars gt
  • 在 C# 中将字符串转换为类型[重复]

    这个问题在这里已经有答案了 如果我收到一个包含类名称的字符串 并且我想将该字符串转换为真实类型 字符串中的类型 我该怎么做 I tried Type GetType System Int32 例如 它似乎有效 但是当我尝试使用自己的对象时
  • 在 XCode 中静态链接 OpenSSL

    我正在尝试链接libssl a and libcrypto aXCode 命令行项目中的静态库 在 Link Binary With Libraries 下 我已在搜索路径中包含 Openssl 头文件 编译成功但执行失败dyld Libr
  • 从滑块输入数据以更改标记颜色

    感谢对此任务的任何帮助 我试图让这个破折号应用程序采用滑块输入值来通过函数更改变量 然后仅更改标记颜色变量 该代码是用 python 编写的 并使用了plotly dash 和plotly 以及pandas numpy 和mapbox 代码
  • 如何防止用户杀死C#应用程序[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 如果您使用 ESET Smart S
  • 我可以访问 TBits 内部位图吗?

    In particular i want to preset desired size fetch a bitmap from external source and then work with data in classy object
  • 使用 UDF 添加文件读取添加到 Hive 资源的文件

    我想知道如何读取使用添加的 Hive 资源ADD FILE来自乌德夫 例如 Hive gt add file users temp key jks Java中的UDF可以读取这个文件吗 在 Udf 中获取此文件的路径是什么 谢谢 大卫 一旦
  • JPEG 颜色在不同浏览器中呈现不一致

    我正在使用的徽标在不同浏览器中的呈现方式有所不同 具体图片可查here https pbs twimg com profile images 741262755236356096 BqpBjB8R jpg and on 这个推特页面 htt
  • RecyclerView 中的单选

    我知道没有默认的选择方法RecyclerView类 但我尝试过以下方式 public void onBindViewHolder ViewHolder holder final int position holder mTextView s
  • 为 SharePoint 2010 Web 部件创建图表

    我已创建从 Web 部件到 Oracle 数据库的连接 其中包含日期和数字 我想在图表中显示这些数据 我在互联网上查找过任何示例 但我很困惑 任何人都可以向我指出一些简单的说明 详细说明如何在 C Sharp 中创建可在 Web 部件上使用
  • 在 ASP.NET MVC 中返回不同的视图同一控制器

    我想根据以下值将用户发送到两个不同页面之一isCustomerEligible 当该变量的值设置为 false 时 它 会调用 Index 但随后返回视图Customer而不是视图Index public ViewResult Index
  • textarea根据内容js或jquery设置高度

    这是我的代码 保持简单
  • 具有单变量优化的 NLopt

    任何人都知道 NLopt 是否适用于单变量优化 尝试运行以下代码 using NLopt function myfunc x grad x 2 end opt Opt LD MMA 1 min objective opt myfunc mi
  • 如何在 pytest 中测试类层次结构?

    我已经使用 pytest 一段时间了 并学会了喜欢参数化和固定装置 我第一次想测试一些具有分支继承结构的类 当然 我想为子类重用测试用例 假设我有以下包结构 mock pkg child py grandchild py parent py
  • EC2 增加大小后无法调整卷大小

    我已按照调整 EC2 卷大小的步骤进行操作 停止实例 拍摄当前卷的快照 在同一区域中从上一个快照创建了一个更大大小的新卷 从实例中分离旧卷 将新卷附加到同一安装点的实例 旧卷是 5GB 我创建的卷是 100GB 现在 当我重新启动实例并运行
  • C 中未声明的标识符

    我正在尝试在 Visual Studio 2012 Express 中用 C 语言编译一个小型银行程序 它向我显示了几乎所有变量的 未声明标识符 错误 以及 语法错误 缺少 在 类型 之前 请告诉我正确的语法 谢谢 include
  • 如何让文字显示5秒然后消失并显示按钮?

    我正在努力做到这一点 以便当您在我的问答游戏中得到正确答案时 它会摆脱您看到的大问题并说 干得好 5秒钟 然后返回到主菜单 其中随机有4个选定的问题 问题从 quizfile csv 加载并包含 What colour is elon mu