我是 pygame 的新手,正在尝试编写在谷歌上互联网中断时播放的恐龙游戏。我注意到,每当我停止在动画窗口上移动鼠标时,帧速率就会下降到 0。我在网上环顾四周,之前似乎没有人谈论过这个问题(或者也许我没有得到我的关键字下)。
如何让它保持以相同的方式移动,无论我的鼠标是否在动画窗口上移动?
这是我的代码:
import pygame
from sys import exit
pygame.init()
pygame.display.set_caption("Runner")
clock = pygame.time.Clock()
display_surface = pygame.display.set_mode((800, 400))
#data values
score = 0
x_bound = 800
y_bound = 400
floor_y = 300
speed = 10
player_gravity = 0
test_font = pygame.font.Font('font/Pixeltype.ttf', 50)
score_surface = test_font.render(f'Score: {score}', False, (64, 64, 64))
sky_surface = pygame.image.load('graphics/Sky.png').convert()
ground_surface = pygame.image.load('graphics/ground.png').convert()
snail_surface = pygame.image.load('graphics/snail/snail1.png').convert_alpha()
player_surface = pygame.image.load('graphics/player/player_walk_1.png').convert_alpha()
#initializing rectangles
player_surface_rect = player_surface.get_rect(midbottom=(80, 300))
snail_surface_rect = snail_surface.get_rect(midbottom=(600, 300))
score_surface_rect = score_surface.get_rect(midtop=(400, 50))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.type == 768: #768 --> spacebar
player_gravity = -15
display_surface.blit(sky_surface, (0, 0))
display_surface.blit(ground_surface, (0, 300))
#score
pygame.draw.rect(display_surface, '#c0e8ec', score_surface_rect)
pygame.draw.rect(display_surface, '#c0e8ec', score_surface_rect, 5)
display_surface.blit(score_surface, score_surface_rect)
#snail
snail_surface_rect.x -= speed
if snail_surface_rect.right <= 0:
snail_surface_rect.left = x_bound
display_surface.blit(snail_surface, snail_surface_rect)
#player
#jump
player_gravity += 1
player_surface_rect.y += player_gravity
#creating floor
if player_surface_rect.bottom > floor_y:
player_surface_rect.bottom = floor_y
display_surface.blit(player_surface, player_surface_rect)
pygame.display.update()
clock.tick(60)
我在网上寻找模块来解决这个问题,但是没有找到任何模块。 我在这个程序中一直遵循 Clear Code 的 pygame 指南
您的整个游戏逻辑都在您的
for event in pygame.event.get():
循环内。
如果没有事件(例如鼠标移动),则不会发生任何事情。
在您的
while True
主循环中,将所有内容从 display_surface.blit(...)
向前移动一层缩进,使其变浅,这样它们就脱离了 for event
循环。