简体   繁体   English

如何优化此代码的性能?

[英]How can I optimize this code for performance?

I'm making a game in pygame, the full source code of which can be found here: 我正在pygame中制作游戏,其完整源代码可以在这里找到:

https://github.com/hailfire006/games/blob/master/strategy%20game https://github.com/hailfire006/games/blob/master/strategy%20game

Unfortunately, I'm running into some frame rate issues and everything I've read about this sort of problem says it's graphical, ie it's got nothing to do with the math and everything to do with drawing the sprites. 不幸的是,我遇到了一些帧速率问题,而我所读到的有关此类问题的所有内容均表示为图形化,即与数学无关,与绘制子画面无关。

As such, I've narrowed the problem down to the following draw function of my npc class, which is called every frame for every npc in my "objects" list. 这样,我将问题缩小到我的npc类的以下绘制函数,该函数在“对象”列表中为每个npc调用每一帧。 It's got a lot of sprite rotation, a set_colorkey, and a re-sizing. 它具有大量的精灵旋转,set_colorkey和调整大小。 All of these things are probably quite costly, so is there a way I can re-write the following code to optimize it for performance? 所有这些事情可能都非常昂贵,所以有没有办法我可以重新编写以下代码以对其性能进行优化?

PS: Sorry if what I'm asking or bits of the code are unclear, point it out if something is confusing and I'll edit my question. PS:对不起,如果我要问的内容或部分代码不清楚,请指出是否有混淆之处,然后我将编辑我的问题。

b = pygame.sprite.Sprite()
b.image = pygame.image.load("soldier.png").convert()
b.image.set_colorkey((0,0,0))

target = get_target(self)
if target != 0:
    angle = math.degrees(math.atan2(self.x - target[0], self.y - target[1])) + 90
    b.image = pygame.transform.rotate(b.image,angle)
    self.shoot(target)

if self.moving != False:
    if abs(self.x - self.moving[0]) < 1 and abs(self.y - self.moving[1]) < 1:
        self.moving = False
    else:
        self.move(self.moving)
        if target == 0:
            angle = math.degrees(math.atan2(self.x - self.moving[0],                   self.y - self.moving[1])) + 90
            b.image = pygame.transform.rotate(b.image,angle)

b.image = pygame.transform.smoothscale(b.image,(50,50))
b.rect = b.image.get_rect()
b.rect.topleft = [self.x - 20, self.y - 20]
window.blit(b.image, b.rect)

Woah woah woah... are you loading and converting that .png every frame? 哇哇哇...您正在每帧加载并转换该.png吗?

  1. Don't do that. 不要那样做

Next up, instead of returning 0 from get_target, I recommend returning None. 接下来,建议不要返回get_target的0,而不要返回。 Then your next line can be: 然后,您的下一行可以是:

if target is not None:

Which is slightly faster. 哪个稍微快一点。

Next time, try and profile each segment of your code. 下次,尝试剖析代码的每个部分。 You can use python's profiling tools to have a look at your code in detail, or just write your own simple timer controller . 您可以使用python的性能分析工具详细查看代码,也可以只编写自己的简单计时器控制器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM