简体   繁体   中英

How to make my game frames not drop in pygame

I have been working on this game and for some reason every time I add this part https://gyazo.com/8efc90c1bb655c140b83b279e42dd73d ,

the fps drops a lot, if you take it out it works good but once you add it back it the the game get super laggy. I have tried taking it out but I want it in, also I have tried putting different levels on the https://gyazo.com/f973f353020018ea56b8773a2c586472

but that did not really work, I have also tried putting the fps higher but that did not work, the last thing I have tried was deleting some of the updates commands but that did not work

what make's my game lag

#####################################
    # LIVES AND SPIKE
    for spike in spikes:
        for one in range(len(spikes)-1-1-1):
            if player1.rect.colliderect(spikes[one].rect):
                if deaths > 0:
                    deaths -= 1
                    talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
                    talkRect.center = ((100,90))
                    del spikes[one]


    for pike in pikes:
        for one in range(len(pikes)-1-1-1):
            if player1.rect.colliderect(pikes[one].rect):
                if deaths > 0:
                    deaths -= 1
                    talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
                    talkRect.center = ((100,90))
                    del pikes[one]


    for live in lives:
        for one in range(len(lives)-1-1-1):
            if player1.rect.colliderect(lives[one].rect):
                if deaths > 0:
                    deaths += 1
                    talkRect.center = ((100,90))
                    del lives[one]
                    
 #########################################################    

my full code

import pygame
pygame.init()

#screen
window = pygame.display.set_mode((500,500))

#set name
pygame.display.set_caption("Noobs First Game")


mad1 = pygame.image.load("MAD1.png")
mad2 = pygame.image.load("MAD2.png")
happy1 = pygame.image.load("happytext1.png")
happy2 = pygame.image.load("happytext2.png")
happy3 = pygame.image.load("happytext3.png")
hapad = pygame.image.load("happymadtext1.png")
end =  pygame.image.load("endtext1.png")

class player:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 6
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.image.load("Me1.png")
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//8,self.ss1.get_height()//8))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        player_rect = self.ss1.get_rect(center = self.rect.center)  # the player_image << put your image like self.image
        player_rect.centerx += +2 # 10 is just an example
        player_rect.centery += -6# 15 is just an example
        window.blit(self.ss1, player_rect) # change the player_image to your image like self.image


class platform:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.image.load("Dirt.png")
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//7,self.ss1.get_height()//7))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        platform_rect = self.ss1.get_rect(center = self.rect.center)  # the player_image << put your image like self.image
        platform_rect.centerx += +2 # 10 is just an example
        platform_rect.centery += -3# 15 is just an example
        window.blit(self.ss1, platform_rect)

class wall:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

    


class spike:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.image.load("Spike.png")
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//2,self.ss1.get_height()//3))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        spike_rect = self.ss1.get_rect(center = self.rect.center)  # the player_image << put your image like self.image
        spike_rect.centerx += +10 # 10 is just an example
        spike_rect.centery += -16# 15 is just an example
        window.blit(self.ss1, spike_rect)


class ice:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 7
        self.ss1 = pygame.image.load("ice.png")
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//1,self.ss1.get_height()//1))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)
       

        
        fall_rect = self.ss1.get_rect(center = self.rect.center)
        fall_rect.centery += 2
        fall_rect.centerx += 1
        window.blit(self.ss1, fall_rect)



class coin:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.ss1 = pygame.image.load("Coin2.png")
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//10,self.ss1.get_height()//10))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        coin_rect  = self.ss1.get_rect(center = self.rect.center)
        coin_rect.centery -= 1
        coin_rect.centerx -= 1
        window.blit(self.ss1,coin_rect)


class recta:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y =y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
    def draw(self):
        self.rect.topleft = (self.x, self.y)

class pike:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.image.load("Spike2.png")
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//2,self.ss1.get_height()//3))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        pike_rect = self.ss1.get_rect(center = self.rect.center)  # the player_image << put your image lik self.image
        pike_rect.centerx += +10 # 10 is just an example
        pike_rect.centery += -12# 15 is just an example
        window.blit(self.ss1, pike_rect)


class live:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,width,height)
        self.ss1 = pygame.image.load("HP.png")
        self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//4,self.ss1.get_height()//4))
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

        pike_rect = self.ss1.get_rect(center = self.rect.center)  # the player_image << put your image lik self.image
        pike_rect.centerx += -5 # 10 is just an example
        pike_rect.centery += -30# 15 is just an example
        window.blit(self.ss1, pike_rect)       




#draw player
white = (255,255,255)
green = (0,200,0) 
player1 = player(0,400,40,40,white)

#PLATFORM
platform1 = platform(0,0,400000,30,green)
platform2 = platform(0,470,400000,30,green)

#WALLS
wall1 = wall(0,0,40000,30,green)
wall2 = wall(0,470,40000,30,green)

#SPIKES
spike1 = spike(400,436,15,35,white)
spike2 = spike(200,436,15,35,white)

#ICE
ice1 = ice(13250,70,25,95,white)
ice2 = ice(13300,70,25,95,white)
ice3 = ice(13350,70,25,95,white)
ice4 = ice(13400,70,25,95,white)

#COINS
coin1 = coin(100,200,35,50,white)
coin2 = coin(100,200,35,50,white)

#RECTA
recta1 = recta(13200,0,600,600,white)
recta2 = recta(34000,0,400,600,white)
recta3 = recta(34400,0,400,600,white)
recta4 = recta(43000,0,400,600,white)
recta5 = recta(43400,0,400,600,white)
recta6 = recta(43800,0,400,600,white)
recta7 = recta(44200,0,400,600,white)
recta8 = recta(44600,0,400,600,white)

#SECOND SPIKES
pike1 = pike(799,799,1,1,white)
pike2 = pike(799,799,1,1,white)

live1 = live(900,900,1,1,white)
live2 = live(900,900,1,1,white)

platforms = [platform1,platform2]
walls = [wall1,wall2]
spikes = [spike1,spike2]
ices = [ice1,ice2,ice3,ice4]
coins = [coin1,coin2]
rectas = [recta1,recta2,recta3,recta4,recta5,recta6,recta7,recta8]
pikes = [pike1,pike2]
lives = [live1,live2]


# MY GAME AND HOW IT LOOKS LIKE
platformGroup = pygame.sprite.Group
level = [
"                                                                                                                                                                                                             ",
"                                                                                                                                                                                                                                                                               ",
"                                                                                                                                                                                                                                                               ",
"                                                                                                                                                                                                                            ",
"                                                                                                                                                                cccc                                                                                                                                                                                                                                                                                                                             c  c                                                                                                                                                                                                                                            psssss               ",
"                                                                                                                                                                c                                                                                                                                                                                                                                                                                                                             c  p  p  pssss                                                                                          p  p  p  p                                                                                                                              p                                                     ",
"                                                                                                               y   y       y   y                                c                                                                                                                              c  c   c                                                                              c     c             y                                                                       c   c  c     p                                                                                                    p                                                                                                                       cccccccccc  p                                               ",
"                                                                                  cc                             c  c  c  c  c                                  cccc                                                                     c   c  c                 c  c   c                                                                                                              p  p  p     c                                                                       c  p  p  p  p  p                                                                 cccccc                    p  p  p  p                                                                                                                          p  p  p  p                                                                                ",                        
"                                                    c  c  c  c                      c                                                            y   y          c                  c   c  c  c        y  y  y                            c   c  c                                            p  p  p  p    c                   y        y      y  y  y          yy   yy         c    p           p  p  p    c            c                            y   y   y             p                 p                                                              cccccc   y             p              p                                                                     y  y  y  y  y                                  p              p                               y   y                           ",
"                             p        y           p  p  p  p  p                ccccccc                         p  p  p  p  p  p  p          p                   c               p   y   y   y                                            ccccc  c               p  p  p  p     c          p   ss ss ss   p                                                                        p                      p  p  p         p                                            c  p                       p                                            p              cccccc              p                    psssss                                                       p                                                 p                    pssss                    p                            ",
"               c  c       p      c    c     k  p                   yyyyyyy          c      yy   yyyy        p                        k   p                      cccc          p                         c  c      yyyyyy    yyyyyyy      c   c  c            p              p          p                   s p    c    c         yyyyy          c   c       c c c c c c       cp                                      p    ss   yyyyyyy   yyyyyyy       c   c         p                             p              y    y    y             p     p    k      cccccc           p                                                           y   y   y   y   y     p                       c             k           p                    yyyyyyyy   yyyyyyy       p                                                              ",
"             s  s  s    p   ssss  c s  s     p    s s s s s s s      c c c        cc     s c  sc  c  s   p      s  s  s  s  s  s  s   p   s s    s   s   s  s  s  s  s  s  p           s   s k  s     s  s  s             s          s   c   c  c     k   p     s s s s s s s s     p     s s s s s s s s       s  s  s  s   k s   c c  s     s  s  s       p cs    s       p      s  s  s  s s s s s s s s s s    p            c c  c  s  c  c   s   s   s   s k  p     s s s s s s s s s s s ss      ccccccc   s    s    s      s  s  s           s  s  s  cccccc   s    p     s s s s s s s s s s s                                  s   s   s   s   s    p           s  s  s  s  s  c  s  s  s  s  s   s   p     sssssssssssssss            s         s  p                                               s   sssss ssssss ssssssssssssss sssssssssss ssssssssssss sssssssssss ssssssss sssssssssss",] 


for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "p":
            new_platforms = platform(ix*57, iy*41.2, 50,20,(255, 255, 255))
            platforms.append(new_platforms)
for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "s":
            new_spikes = spike(ix*57, iy*39.7, 15, 35,(255, 255, 255))
            spikes.append(new_spikes)
for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "c":
            new_coins = coin(ix*57, iy*39.7, 15, 35,(255, 255, 255))
            coins.append(new_coins)
for iy, row in enumerate(level):
    for ix, col in enumerate(row):            
        if col == "y":
            new_pikes = pike(ix*57, iy*39.7, 15, 30,(255, 255, 255))
            pikes.append(new_pikes)

for iy, row in enumerate(level):
    for ix, col in enumerate(row):            
        if col == "k":
            new_lives = live(ix*57, iy*39.7, 30, 30,(255, 255, 255))
            lives.append(new_lives)


            
#redraw
def redrawwindow():
    window.fill((0,0,0))

                
    

#draw olayer
    player1.draw()
    for platform in platforms:
        platform.draw()
    for wall in walls:
        wall.draw()
    for spike in spikes:
        spike.draw()
    for ice in ices:
        ice.draw()
    for coin in coins:
        coin.draw()
    for recta in rectas:
        recta.draw()
    for pike in pikes:
        pike.draw()
    for live in lives:
        live.draw()


 # the score draw it on the screen
    window.blit(text,textRect)
    window.blit(talk,talkRect)


fps = (30)
clock = pygame.time.Clock()


#THE FONT AND NAMES
font  = pygame.font.Font("freesansbold.ttf",30)
score = 0
text = font.render("Coins = "+str(score),True,(255,255,255))
textRect = text.get_rect()
textRect.center = ((100,50))


font  = pygame.font.Font("freesansbold.ttf",30)
deaths = 5
talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
talkRect = talk.get_rect()
talkRect.center = ((100,90))



#MAIN LOOP
run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
#####################################
    # LIVES AND SPIKE
    for spike in spikes:
        for one in range(len(spikes)-1-1-1):
            if player1.rect.colliderect(spikes[one].rect):
                if deaths > 0:
                    deaths -= 1
                    talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
                    talkRect.center = ((100,90))
                    del spikes[one]


    for pike in pikes:
        for one in range(len(pikes)-1-1-1):
            if player1.rect.colliderect(pikes[one].rect):
                if deaths > 0:
                    deaths -= 1
                    talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
                    talkRect.center = ((100,90))
                    del pikes[one]


    for live in lives:
        for one in range(len(lives)-1-1-1):
            if player1.rect.colliderect(lives[one].rect):
                if deaths > 0:
                    deaths += 1
                    talkRect.center = ((100,90))
                    del lives[one]
                    
 #########################################################               
    #ADDING TO COIN +1
    for coin in coins:
        for one in range(len(coins)-1,-1,-1):
            if player1.rect.colliderect(coins[one].rect):
                del coins[one]
                score += 1
                text = font.render("Coins = "+str(score),True,(255,255,255))
                textRect.center = ((100,50))

    

    
    #moving keys
    keys = pygame.key.get_pressed()


    player1.x += player1.speed

    #WHAT MAKES ICEBURG FALL
    for ice in ices:
        if player1.rect.colliderect(recta1.rect):
            ice.y += 3


        


    
    #WHAT MAKES EVEYTHING NOT FOLLOW THE PLAYER    
    if player1.x > 250:
        player1.x -= player1.speed
        for platform in platforms:
            platform.x -= player1.speed
        for spike in spikes:
            spike.x -= player1.speed
        for ice in ices:
            ice.x -= player1.speed
        for recta in rectas:
            recta.x -= player1.speed
        for pike in pikes:
            pike.x -= player1.speed
        for coin in coins:
            coin.x -= player1.speed
        for live in lives:
            live.x -= player1.speed



     #FALLING   
    if not player1.isJump:
        player1.y += player1.fall
        player1.fall += 1
        player1.isJump = False



            
        #COLLIDE WITH PLATFORM
        collide = False
        for platform in platforms:
            if player1.rect.colliderect(platform.rect):
                collide = True
                player1.isJump = False
                player1.y = platform.rect.top - player1.height + 1
                if player1.rect.right > platform.rect.left and player1.rect.left < platform.rect.left - player1.width:
                    player1.x = platform.rect.left - player1.width
                if player1.rect.left < platform.rect.right and player1.rect.right > platform.rect.right + player1.width:
                    player1.x = platform.rect.right
                              

            #COLLIDE
            if player1.rect.bottom >= 500:
                collide = True
                player1.isJump = False
                player1.JumpCount = 8
                player1.y = 500 - player1.height

                
        #KEY FOR SPACEBAR
        if collide:
            if keys[pygame.K_SPACE]:
                player1.isJump = True
            player1.fall = 0


    #JUMP COUNT
    else:
        if player1.JumpCount >= 0:
            player1.y -= (player1.JumpCount*abs(player1.JumpCount))*0.2
            player1.JumpCount -= 1
        else:
            player1.JumpCount = 10
            player1.isJump = False
        


#END OF GAME            
    redrawwindow()
    

    # TEXT THAT CORATOR IS SAYING
    if player1.rect.colliderect(recta2):
        window.blit(mad1,(100,170))
        
    if player1.rect.colliderect(recta3):
        window.blit(mad2,(100,170))

    if player1.rect.colliderect(recta4):
        window.blit(happy1,(100,100))

    if player1.rect.colliderect(recta5):
        window.blit(happy2,(100,100))    

    if player1.rect.colliderect(recta6):
        window.blit(happy3,(100,100))

    if player1.rect.colliderect(recta7):
        window.blit(hapad,(100,100))

    if player1.rect.colliderect(recta8):
        window.blit(end,(100,100))
        
    pygame.display.update()
pygame.quit()


Concerning the lag section, there's a few things:

  • As @Kingsley mentioned, you're double looping, squaring the numbers of collision checks
  • You're checking objects that aren't on the screen
  • Your deleting objects while iterating them (probably explains the -1-1-1)

Try this code. It moves much faster:

#     LIVES AND SPIKE
    lstdel = []
    for i,spk in enumerate(spikes):
        if spk.rect.left > 500 or spk.rect.left < 0: continue  # off screen
        if player1.rect.colliderect(spk.rect):
            if deaths > 0:
                deaths -= 1
                talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
                talkRect.center = ((100,90))
                lstdel.append(i)
    for i in lstdel[::-1]:
        del spikes[i]  #delete from end
  
    lstdel = []
    for i,pk in enumerate(pikes):
        if pk.rect.left > 500 or pk.rect.left < 0: continue  # off screen
        if player1.rect.colliderect(pk.rect):
            if deaths > 0:
                deaths -= 1
                talk = font.render("LIVES = "+str(deaths),True,(255,255,255))
                talkRect.center = ((100,90))
                lstdel.append(i)
    for i in lstdel[::-1]:
        del pikes[i]  #delete from end
  
    lstdel = []
    for i, lv in enumerate(lives):
        if lv.rect.left > 500 or lv.rect.left < 0: continue  # off screen
        if player1.rect.colliderect(lv.rect):
            if deaths > 0:
                deaths += 1
                talkRect.center = ((100,90))
                lstdel.append(i)
    for i in lstdel[::-1]:
        del lives[i]  #delete from end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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