gpt4 book ai didi

Python Pygame 正在变慢

转载 作者:行者123 更新时间:2023-12-01 06:45:55 26 4
gpt4 key购买 nike

我正在使用 pygame 创建一个 Python 游戏。游戏运行良好,但我向游戏中添加的角色越多,游戏速度就越慢。我该如何修复它?

这是主要代码:

finish = False
background_x = 0
background_y = 0
REFRESH_RATE = 180
background = pygame.image.load(BACKGROUND_IAMGE)

while not finish:
clock.tick(REFRESH_RATE)
SCREEN.blit(background, (background_x, background_y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True

block_on_right = False
block_on_left = False
is_player_on_block = False
for block in blocks:
block.load_image(background_x)
if player.is_crash(block):
for i in range(player.vy):
if player.get_bottom_y() - i == block.get_y():
is_player_on_block = True
if player.y + i == block.get_bottom_y():
player.set_jump(False)
for i in range(player.vx):
if player.get_right_x() - i == block.get_x():
block_on_right = True
if player.x + i == block.get_right_x():
block_on_left = True
for monster in monsters:
if monster.is_crash(block):
monster.turn_around()

keys = pygame.key.get_pressed()

if (keys[pygame.K_UP] or keys[pygame.K_SPACE] or keys[pygame.K_w]) and not player.is_mid_air():
player.set_jump(True)

if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and not block_on_right:
if player.get_direction() != "right":
player.turn_around()
player.set_walk(True)

background_x -= player.vx
player.x += player.vx

if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and not block_on_left:
if player.get_direction() != "left":
player.turn_around()
player.set_walk(True)
if background_x != 0:
background_x += player.vx
player.x -= player.vx

if not any(keys):
player.stand_still()
player.set_walk(False)

for monster in monsters:
SCREEN.blit(monster.get_image(), (background_x + monster.get_x(), monster.get_y()))
monster.step()

if player.get_bottom_y() == FLOOR_Y or is_player_on_block:
player.set_is_mid_air(False)
else:
player.set_is_mid_air(True)
player.fall()

player.check_jump()

player_image = player.get_image().convert()
player_image.set_colorkey(PINK)

SCREEN.blit(player_image, (player.x + background_x, player.y))
pygame.display.flip()

pygame.quit()

最佳答案

我不是有效减少执行时间的专家,但有一些技巧(看看它们是否有帮助)。
首先,看看是否可以降低刷新率。
其次,我注意到你每次迭代都会重新绘制背景。我认为有一种方法可以只更新屏幕的一部分。因此,您应该能够绘制一次背景,然后仅重绘角色所在的屏幕部分。这可能会有所帮助,特别是如果您的背景是静态的。
如果仍然较慢,请看看是否可以减小图像的尺寸(可能是一个坏主意,但值得一试)
希望至少其中一些是可以实现的。

关于Python Pygame 正在变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com