很多人无论是看书还是看视频的时候,总是喜欢照搬别人的代码,按照原来的文字来解释,关于pygame我所有的程序几乎都参考于《Beginning Game Development with Python and Pygame》,在书的第三节的最后的一个例子说的是一个跑马灯的例子,本来这没有什么需要,在pygame里面,实现跑马灯就是当作图片来渲染,这个小程序有两个需要注意的地方,第一个是文本的渲染次数,因为是跑马灯,所以必须让文字看起来是连续的,因为文本够长,这里就只渲染来两次,好奇的人可以注释其中一个渲染,然后看看效果,还有一个就是,我最后渲染的时候,使用来双缓冲来实现的,这样的好处在于加载大文件或者是图片其他的效果会好很多,直接贴代码。
background_image_filename = 'sushiplate.png'
SCREEN_SIZE = (640, 480)
message=" This is a demonstration of the scrolly message script. "
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
font = pygame.font.SysFont("arial", 80);
text_surface = font.render(message, True, (0, 0, 255))
x =0
y = ( SCREEN_SIZE[1] - text_surface.get_height() ) / 2
background = pygame.image.load(background_image_filename).convert()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x-= 2
if x < -text_surface.get_width():
x = 0
# the reason to blit twice is to let the marquee look consecutively
screen.blit(text_surface, (x, y))
screen.blit(text_surface, (x + text_surface.get_width(), y))
#use a double-buffered display
pygame.display.flip()