简体   繁体   中英

how do I make my crash function restart my game?

So I been trying to make my crash function restart my whole game when the player's live's reaches to 0 but it dose not work

https://gyazo.com/3a039c5d9af3a6868c278c39939314cf

as you can see from the video, it only restarts my lives when the it reaches 0, also it quickly shows the "you crashed" text but I want it to show for a little bit then restart my game. I have tried calling the main_loop with the crash function but that dose not change anything also I have tried putting the code that calls the crash function and makes the game restart above my start screen but that did not work to.

this is what I wrote for my restart game function

black = (0,0,0)
def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',25)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((500/2),(500/2))
    window.blit(TextSurf, TextRect)

    pygame.display.update()
    main_loop()
    time.sleep(2)

My full code also I wrote an if state-mate about if my deaths < 1 I wanted it to restart my game but it only will restart my life

import pygame,time
pygame.init()

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

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

bg = pygame.image.load("leafy_background.jpg")
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")
ss1 = pygame.image.load("Coin2.png")
ss1 = pygame.transform.scale(ss1,(ss1.get_width()//12,ss1.get_height()//12))
ss2 = pygame.image.load("HP.png")
ss2 = pygame.transform.scale(ss2,(ss2.get_width()//5,ss2.get_height()//5))

black = (0,0,0)
def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',25)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((500/2),(500/2))
    window.blit(TextSurf, TextRect)

    pygame.display.update()
    main_loop()
    time.sleep(2)


    
    

def crash():
    message_display('You Crashed')
    
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) 
player1 = player(0,400,40,40,white)

darkred = (200,0,0)

darkgreen = (0,200,0)

green = (0,255,0)

red = (255,0,0)

black = (0,0,0)

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

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

#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(34450,0,400,600,white)
recta4 = recta(43000,0,400,600,white)
recta5 = recta(43450,0,400,600,white)
recta6 = recta(43900,0,400,600,white)
recta7 = recta(44250,0,500,600,white)
recta8 = recta(44800,0,500,600,white)

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

live1 = live(43000,350,30,30,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     sssssssssss                s         s  p                                                             ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss",] 


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, 55,(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)


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

        
#################
def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    #print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac,(x,y,w,h))

        if click[0] == 1 and action != None:
            action()         
    else:
        pygame.draw.rect(window, ic,(x,y,w,h))

    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    window.blit(textSurf, textRect)

def quitgame():
    pygame.quit()

def unpause():
    global pause
    pause = False
    
def paused():

    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("Paused", largeText)
    TextRect.center = ((500/2),(500/2))
    window.blit(TextSurf, TextRect)
    

    while pause:
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
                
        

        button("Can Run",100,350,100,50,green,darkgreen,unpause)
        button("Sit",300,350,100,50,red,darkred,quitgame)
        
        pygame.display.update()
        clock.tick(15)


        
    
def game_intro():

    intro = True

    while intro:
        for event in pygame.event.get():
            #print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        window.fill((255,255,255))
        largeText = pygame.font.Font('freesansbold.ttf',60)
        TextSurf, TextRect = text_objects("ULTIMATE DASH", largeText)
        TextRect.center = ((500/2),(500/2))
        window.blit(TextSurf, TextRect)

        button("Run!",100,350,100,50,green,darkgreen,main_loop)
        button("Sit!",300,350,100,50,red,darkred,quitgame)

        pygame.display.update()
        clock.tick(15)
     
############################################




def main_loop():
    global pause

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

                    
        

    #draw olayer
        player1.draw()
        for platform in platforms:
            platform.draw()
        for wall in walls:
            wall.draw()
        for ice in ices:
            ice.draw()
        for recta in rectas:
            recta.draw()
        


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

        for spike in spikes:
            spike.draw()
        for coin in coins:
            coin.draw()
        for pike in pikes:
            pike.draw()
        for live in lives:
            live.draw()



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


    font  = pygame.font.Font("freesansbold.ttf",30)
    deaths = 5
    talk = font.render(" = "+str(deaths),True,(0,0,0))
    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
        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(" = "+str(deaths),True,(0,0,0))
                    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(" = "+str(deaths),True,(0,0,0))
                    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
                    talk = font.render(" = "+str(deaths),True,(0,0,0))
                    talkRect.center = ((100,90))
                    lstdel.append(i)
        for i in lstdel[::-1]:
            del lives[i]
            
        #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(" = "+str(score),True,(0,0,0))
                    textRect.center = ((100,50))

        

        if deaths < 1:
            crash()

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


        player1.x += player1.speed

        if keys[pygame.K_p]:
            pause = True
            paused()

        #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))

        window.blit(ss1,(30,25))
        
        window.blit(ss2,(-40,-20))
            
        pygame.display.update()
    pygame.quit()
    unpause()
game_intro()
main_loop()



To things need to be done to restart your game.

  • The code that initializes the variables should be put in a function so it can be called to restart the game.
  • In the main loop, when crash is called, it should also return to exit the game loop.

Note that I merged the files together for testing.

Here are the changes....

After the pygame calls (image loads):

white=None; player1=None; darkred=None; darkgreen=None; green=None; red=None; black=None; platform1=None; platform2=None; wall1=None; wall2=None; spike1=None; spike2=None
ice1=None; ice2=None; ice3=None; ice4=None; coin1=None; coin2=None; recta1=None; recta2=None; recta3=None; recta4=None; recta5=None; recta6=None; recta7=None; recta8=None
pike1=None; pike2=None; live1=None; live2=None; platforms=None; walls=None; spikes=None; ices=None; coins=None; rectas=None; pikes=None; lives=None; platformGroup=None

black = (0,0,0)
darkred = (200,0,0)
darkgreen = (0,200,0)
green = (0,255,0)
red = (255,0,0)
black = (0,0,0)

After the live class:

def SetupGame():
    global white, player1, darkred, darkgreen, green, red, black, platform1, platform2, wall1, wall2, spike1, spike2
    global ice1, ice2, ice3, ice4, coin1, coin2, recta1, recta2, recta3, recta4, recta5, recta6, recta7, recta8
    global pike1, pike2, live1, live2, platforms, walls, spikes, ices, coins, rectas, pikes, lives, platformGroup 

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

    .............

    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)

In the game loop

def main_loop():
    SetupGame()  # initialize variables
    global pause

    ..........

    if deaths < 1:
        crash()
        sleep(2)  # 2 seconds
        return  # restart game

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