2015-08-24 122 views
2

如何在PyGame中闪烁文字?下面是一段文字,我想闪烁一次每秒左右: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) 

回答

2

为了有它闪烁,你必须画出它的第二个然后删除它的第二个重复此,再次。为了定时闪烁,可以使用自定义定时器事件。

#!/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的闪烁文本封装起来,可能有助于在初始化和主循环中保持清晰的代码。