问题描述
我一直在使用 pygame 制作一个简单的 python 游戏,在我添加了切换枪支的功能后,游戏开始滞后.我不知道为什么它滞后.我试过重新启动,但没有奏效.代码真的很短,所以也许它只是我的电脑,但如果有什么可以帮助它更快地运行,请告诉我.代码如下:
I have been making a simple python game using pygame and after I added the feature of switching guns the game started to lag. I have no idea why it is lagging. I have tried rebooting but it didn't work. The code is really short so maybe it is just my computer, but if there is anything that may help run it faster please let me know. Here is the code:
import sys, pygame, pygame.mixer
from pygame.locals import *
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Blue Screen of Death')
#variables
x = 100
y = 200
gun_type = "gun1"
gun = pygame.image.load("gun1.png")
gun = pygame.transform.scale(gun,(500,250))
gun_sound = pygame.mixer.Sound("gun_sound.wav")
clock = pygame.time.Clock()
while 1:
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
gun_sound.play()
elif event.type == KEYDOWN and event.key == K_1:
gun = pygame.image.load("gun1.png")
gun = pygame.transform.scale(gun,(500,250))
gun_type = "gun2"
elif event.type == KEYDOWN and event.key == K_2:
gun = pygame.image.load("gun2.png")
gun = pygame.transform.scale(gun,(500,250))
gun_type = "gun2"
elif event.type == KEYDOWN and event.key == K_TAB:
if gun_type == "gun2":
gun_type = "gun2_aimed"
elif gun_type == "gun2_aimed":
gun_type = "gun2"
elif gun_type == "gun2_aimed":
gun = pygame.image.load("gun2_aimed.png")
gun = pygame.transform.scale(gun,(500,250))
#frames per second
clock.tick(60)
hallway = pygame.image.load("hallway.png")
hallway = pygame.transform.scale(hallway,(600,400))
screen.blit(hallway,(0,0))
screen.blit(gun,(mx-100,y))
pygame.display.flip()
感谢您的帮助.
推荐答案
这可能是您在 Pygame
中可以学到的最重要的东西.
This is probably the most important thing you can learn in Pygame
.
多年来,我一直在 Pygame
中遇到滞后问题.我很沮丧,几乎切换到 Pyglet
.我的游戏仅以 9 fps 运行.
For many years, I've had lagging issues in Pygame
. I was frustrated, and almost switched to Pyglet
. My game was only running at 9 fps.
然后我在我的电脑上找到了一些 Pygame
文档.它从 David Clark 那里得到了一些建议,他建议您在所有 Pygame
图像加载的末尾添加 .convert_alpha()
.这将我的帧率提高到 32!
Then I found some Pygame
documentation on my computer. It had some advice from David Clark, and he suggested you add .convert_alpha()
at the end of all Pygame
image loads. This increased my framerate to 32!
这是网站:
https://www.pygame.org/docs/tut/newbieguide.html
我总是只是创建一个函数来为我做这件事,所以我不必多次输入.convert_alpha()":
I always just create a function to do it for me, so I don't have to keep typing '.convert_alpha()' too many times:
def loadify(imgname):
return pygame.image.load(imgname).convert_alpha()
使用此函数时,只需将 pygame.image.load(
替换为 loadify(
即可.
Just replace pygame.image.load(
to loadify(
when using this function.
玩得开心 Pygame!
Have fun with Pygame!
这篇关于为什么我的简单 pygame 滞后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!