在一个游戏中,显示的控制也是一个比较重要的东西,在不同的机器上,界面刷新的频率不一样(也就是fps不一样),这样照成的结果就是
在不同情况下,基于帧的动画的效果会不同,本次将控制帧率
显示帧率
一般来说,pygame提供了一个控制帧率的方法,但是在低端机会照成帧率跟不上的情况,我们先显示一下帧率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import pygame from pygame import QUIT
pygame.init()
screen = pygame.display.set_mode((300,150),0,32)
font = pygame.font.SysFont('arial', 16)
running = True
mouse = (0,0) mouse_move = (0,0) mouse_key = None text = 'fps: %s' fps = 0 FPS_MAX = 60
clock = pygame.time.Clock()
while running: for event in pygame.event.get(): if event.type == QUIT: running = False
screen.fill((0xff,0xff,0xff)) text_surface = font.render(text % fps ,True,(0xff,0,0)) screen.blit(text_surface,(0,0)) pygame.display.flip() passed_time = clock.tick() print(passed_time) if passed_time <=0 : passed_time = 1 fps = int(1/passed_time*1000)
pygame.quit()
|
帧率
因为我们没有进行什么比较消耗时间的操作,帧率非常快,1秒钟刷新了1000次左右,现在我们来限制帧率
使用 tick 限制帧率
在pygame中,tick方法可以限制最高帧率 (Frame Per Second)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import pygame from pygame import QUIT
pygame.init()
screen = pygame.display.set_mode((300,150),0,32)
font = pygame.font.SysFont('arial', 16)
running = True
mouse = (0,0) mouse_move = (0,0) mouse_key = None text = 'fps: %s' fps = 0 FPS_MAX = 60
clock = pygame.time.Clock()
def get_fps(passed_time): if passed_time <=0 : passed_time = 1 return int(1/passed_time*1000)
while running: for event in pygame.event.get(): if event.type == QUIT: running = False
screen.fill((0xff,0xff,0xff)) text_surface = font.render(text % fps ,True,(0xff,0,0)) screen.blit(text_surface,(0,0)) pygame.display.flip() passed_time = clock.tick(FPS_MAX) fps = get_fps(passed_time)
pygame.quit()
|
手动限制帧率
如果没有 tick 方法的话,我们可以通过计算时间来限制帧率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import pygame from pygame import QUIT
pygame.init()
screen = pygame.display.set_mode((300,150),0,32)
font = pygame.font.SysFont('arial', 16)
running = True
mouse = (0,0) mouse_move = (0,0) mouse_key = None text = 'fps: %s' fps = 0 FPS_MAX = 60 fps_time = 1000/FPS_MAX;
clock = pygame.time.Clock()
def get_fps(passed_time): if passed_time <=0 : passed_time = 1 return int(1/passed_time*1000)
while running: start_time = pygame.time.get_ticks() for event in pygame.event.get(): if event.type == QUIT: running = False
screen.fill((0xff,0xff,0xff)) text_surface = font.render(text % fps ,True,(0xff,0,0)) screen.blit(text_surface,(0,0)) pygame.display.flip() passed_time = pygame.time.get_ticks() - start_time if fps_time > passed_time: pygame.time.wait(int(fps_time - passed_time)) passed_time = pygame.time.get_ticks() - start_time fps = get_fps(passed_time)
pygame.quit()
|