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.