0

I am creating a simlation using tkinter and Pygame and I am currently having trouble optimizing my code. The program needs to draw 500-1000 "ant" sprites to the surface - the behavior of these ants is defined by this class

class Particle(pygame.sprite.Sprite):

    def __init__(self,color,width,height):
        # call parent class constructor
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(ANT_SPRITE_PATH)

        self.rect = self.image.get_rect()
        self.WIDTH = width
        self.HEIGHT = height

    def updatePos(self,pos):
        self.rect.x = pos[0]
        self.rect.y = pos[1]

In the initialization of another class,PyGameWin, instances of Particle are created like so:

self.ants = [Particle('black',1,1) for x in range(500)]

in the event loop of the pygame window, when a "start" button in tkinter has been pressed the following code is executed:

t = threading.Thread(target=self.startAntMotion)
t.start()

where startAntMotion() is defined as follows:

def startAntMotion(self):
    for ant in self.ants[0:100]:
        ant.updatePos(self.start)
        self.surface.blit(ant.image,ant.rect)

        pygame.display.update()

I intend to add more threads for the remaining 400 objects in self.ants in the future. When the program is run and the start button in tkinter is pressed it takes a very long time for the "ants" to be drawn to the screen. Is there any way of optimizing the code so it can run faster? The code that takes longest to execute is the actual drawing of the sprites to the screen.

joyalrj22
  • 115
  • 4
  • 12
  • 4
    Perhaps try calling `pygame.display.update()` after the loop? – Rushy Panchal Oct 22 '16 at 21:18
  • Part of the problem may be the fact that `pygame` doesn't support multithreading. You may need to do something like [this](http://stackoverflow.com/a/7362993/355230). – martineau Oct 22 '16 at 23:31
  • If performance still is an issue after the other fixes suggested on the page, you might consider switching over to an OpenGL binding like pyopengl that is 3d hardware accelerated for a significant performance boost. It would require a significant rewrite of the rendering code, although you can still use pygame for creating the window, loading images, and handling events. – CodeSurgeon Oct 23 '16 at 04:03

1 Answers1

1

I haven't gotten enough +rep to comment but, an efficient way to loading images is written like this: pygame.image.load(ANT_SPRITE_PATH).convert_alpha()

Let me know if that boosted your performance!