PyGam中闪烁的文本

2024-10-01 02:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在PyGame中生成闪烁的文本?下面是我想每隔一秒闪现一次的文字:

text = pygame.font.Font("c:/windows/fonts/visitor1.ttf", 50)

textsurf, textrect = text_objects("Press Any Key To Start", text)

textrect.center = ((res_w / 2), (res_h / 2))

screen.blit(textsurf, textrect)

Tags: text文本objectswindowsfontsresttfpygame
1条回答
网友
1楼 · 发布于 2024-10-01 02:20:56

为了让它闪烁,你必须画一秒钟,然后删除它一秒钟,重复这个过程一遍又一遍。对于闪烁计时,可以使用自定义计时器事件。在

#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
from itertools import cycle
import pygame

VISITOR_TTF_FILENAME = '/usr/share/fonts/truetype/aenigma/visitor1.ttf'
BLINK_EVENT = pygame.USEREVENT + 0


def main():
    pygame.init()
    try:
        screen = pygame.display.set_mode((800, 600))
        screen_rect = screen.get_rect()

        clock = pygame.time.Clock()

        font = pygame.font.Font(VISITOR_TTF_FILENAME, 50)
        on_text_surface = font.render(
            'Press Any Key To Start', True, pygame.Color('green3')
        )
        blink_rect = on_text_surface.get_rect()
        blink_rect.center = screen_rect.center
        off_text_surface = pygame.Surface(blink_rect.size)
        blink_surfaces = cycle([on_text_surface, off_text_surface])
        blink_surface = next(blink_surfaces)
        pygame.time.set_timer(BLINK_EVENT, 1000)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == BLINK_EVENT:
                    blink_surface = next(blink_surfaces)

            screen.blit(blink_surface, blink_rect)
            pygame.display.update()
            clock.tick(60)
    finally:
        pygame.quit()


if __name__ == '__main__':
    main()

与其在关闭阶段完全变黑,还可以在较暗的颜色中闪烁文本。在

如果初始化和主循环中有更多的操作,将闪烁的文本封装在Pygame的Sprite派生的类型中可能有助于保持代码的清晰。在

相关问题 更多 >