如何在 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)
请您参考如下方法:
为了让它闪烁,你必须画它一秒钟然后删除它一秒钟,一遍又一遍地重复这个过程。可以使用自定义计时器事件来计时闪烁。
#!/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()
除了在关闭阶段完全变黑之外,还可以将文本以较深的颜色进行 blit。
如果在初始化和主循环中进行更多操作,将闪烁文本封装在从 Pygame 的 Sprite 派生的类型中可能有助于保持代码清晰。
