I was trying to see what is the highest number of moving and colliding boxes (sprites) I could get in pygame? So that I could start working on game I want, I searched google and I found different people do it as a challenge, trying to get to the highest number of sprites. But none of them use the colliding, they just make a high number of sprites with no for loop inside the main loop.
The highest number I could get before it started to lag was just 260, which is too low for the game I want to start making.
Here is my code:
import pygame
from pygame.locals import*
import time
screen=pygame.display.set_mode((1250,720))
class Box(pygame.sprite.DirtySprite):
def __init__(self,posx,posy):
pygame.sprite.DirtySprite.__init__(self)
self.image= pygame.Surface ([40,40]).convert_alpha()
self.image.fill((250,0,0))
self.rect=self.image.get_rect()
self.rect.center=(posx,posy)
def update (self):
self.dirty=1
pygame.init()
clock=pygame.time.Clock()
boxs=pygame.sprite.LayeredDirty()
while True :
start = time.time()
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type==pygame.QUIT :
pygame.quit()
quit()
if event.type== pygame.MOUSEBUTTONDOWN and event.button == 1:
box=Box(event.pos[0],event.pos[1])
inside=pygame.sprite.spritecollideany(box,boxs )
if not inside :
boxs.add(box)
elif event.type== pygame.MOUSEBUTTONDOWN and event.button == 3:
print (boxs)
elif event.type==KEYDOWN:
if event.key==K_SPACE:
boxs.empty()
for box in boxs :
if box.rect.y<650 :
## touch= pygame.sprite.spritecollideany(box, boxs)
## if touch==box:
##this way above didnt work for me because the box will cross any other box added to the group after it
##for example the box number 3 in the boxs will cross box number 4,5,6,7,8,9,........
touch= pygame.sprite.spritecollide(box, boxs,False)
if (len(touch))<2:# i do this because (touch) will always return that the box touch it self
# but when its touch more then one then i know it touch other box so it will not move
# and i feel that there is much faster way to do this check then my way :(
box.rect.move_ip(0,1)
boxs.update()
dirty=boxs.draw(screen)
pygame.display.update(dirty)
clock.tick(60)
end = time.time()
print (end-start)
#the best until time totally turn to 0.02xxxx = 260 sprite
So what else I could do to have more then 260 moving and colliding boxes at 60 fps without lag?