2017-07-31 8 views
1

Je suis novice en programmation, et j'essaye de faire un simple jeu de voitures en utilisant pygame, tout fonctionne bien jusqu'à ce que j'essaie de faire apparaître des voitures de manière aléatoire, j'ai réussi à faire des rectangles apparaissent au hasard, mais quand je voulais utiliser un sprite de rectangles, il ne fonctionne pas, les erreurs que j'ai obtenu sont les suivantes:Créer aléatoirement des images en pygame

Traceback (most recent call last): File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 241, in game_intro() File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 158, in game_intro button("START",150,450,100,50,red,green,'Play') File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 89, in button game_loop() File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 190, in game_loop truck(tx,ty) File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 32, in truck gameDisplay.blit(truck(tx,ty)) File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 32, in truck gameDisplay.blit(truck(tx,ty)) File "C:/Users/saifo/PycharmProjects/untitled/gamev2.py", line 32, in truck gameDisplay.blit(truck(tx,ty)) [Previous line repeated 992 more times] RecursionError: maximum recursion depth exceeded

et voici mon code,

import pygame 
import time 
import random 
pygame.init() 

pygame.mixer.music.load('C:/Users/saifo/Downloads/Documents/sprites/khaled.mp3') 
crash_sound= pygame.mixer.Sound('C:/Users/saifo/Downloads/Documents/sprites/crash.wav') 
height=600 
width=800 
white=(255,255,255) 
black=(0,0,0) 
red=(255,0,0) 
green=(0,255,0) 
bleu=(0,0,255) 

#x_change=0 
gameDisplay= pygame.display.set_mode((width,height)) 
pygame.display.set_caption('Racing') 
clock =pygame.time.Clock() 

carImg = pygame.image.load('C:/Users/saifo/Downloads/Documents/sprites/viper.png') 
backImg = pygame.image.load('C:/Users/saifo/Downloads/Documents/sprites/back.png') 
truck = pygame.image.load('C:/Users/saifo/Downloads/Documents/sprites/truck.png') 
carImg = pygame.transform.scale(carImg,(100,100)) 
truck = pygame.transform.scale(truck,(100,100)) 
backImg=pygame.transform.scale(backImg,(800,600)) 
carWidth =100 
pause = False 
pygame.display.set_icon(carImg) 

def truck(tx,ty): 
    gameDisplay.blit(truck(tx,ty)) 

# def things (thingx,thingy,thingw,thingh,color): 
#  pygame.draw.rect(gameDisplay,color,[thingx,thingy,thingw,thingh]) 

def car(x,y): 
    gameDisplay.blit(carImg,(x,y)) 

def dodged(count): 
    font =pygame.font.SysFont(None,25) 
    text =font.render("Dodged :" + str(count),True,white) 
    gameDisplay.blit(text,(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',80) 
    textSurf,textRect = text_objects(text,largeText) 
    textRect.center=((width/2),(height/2)) 
    gameDisplay.blit(textSurf,textRect) 

    pygame.display.update() 

    time.sleep(2) 
    game_loop() 

def crash(): 
    pygame.mixer.music.stop() 
    pygame.mixer.Sound.play(crash_sound) 
    message_display('you crashed') 

def button(msg,x,y,w,h,a,i,action=None): 


    mouse = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed() 
    #print(click,mouse) 
    if x + w > mouse[0] > x and y + h > mouse[1] > y: 
     pygame.draw.rect(gameDisplay, a, (x, y, w, h)) 
     if click[0]==1 and action!=None: 
      if action=='Play': 
       game_loop() 
      elif action=='Quit': 
       pygame.QUIT 
       quit() 
      elif action=='Resume': 
       unpause() 

    smalltext = pygame.font.Font('freesansbold.ttf', 25) 
    textsurf ,textrect=text_objects(msg,smalltext) 
    textrect.center=((x+(w/2)),(y+(h/2))) 
    gameDisplay.blit(textsurf,textrect) 
    pygame.display.update() 

def unpause(): 
    global pause 
    pause = False 
    pygame.mixer.music.unpause() 


def paused(): 
    pygame.mixer.music.pause() 
    while pause: 

     for event in pygame.event.get(): 
      if event.type== pygame.QUIT: 
       pygame.quit() 
       quit() 

     gameDisplay.fill(white) 
     largeText = pygame.font.Font('freesansbold.ttf', 80) 
     textSurf, textRect = text_objects("PAUSED", largeText) 
     textRect.center = ((width/2), (height/2)) 
     gameDisplay.blit(textSurf, textRect) 


     pygame.draw.rect(gameDisplay,green,(150,450,100,50)) 
     pygame.draw.rect(gameDisplay,bleu,(550,450,100,50)) 

     button("RESUME",150,450,120,50,red,green,'Resume') 
     button("QUIT",550,450,110,50,red,bleu,'Quit') 



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


def game_intro(): 
    intro = True 

    while intro: 

     for event in pygame.event.get(): 
      if event.type== pygame.QUIT: 
       pygame.quit() 
       quit() 

     gameDisplay.fill(white) 
     largeText = pygame.font.Font('freesansbold.ttf', 80) 
     textSurf, textRect = text_objects("Formula 00", largeText) 
     textRect.center = ((width/2), (height/2)) 
     gameDisplay.blit(textSurf, textRect) 


     pygame.draw.rect(gameDisplay,green,(150,450,100,50)) 
     pygame.draw.rect(gameDisplay,bleu,(550,450,100,50)) 

     button("START",150,450,100,50,red,green,'Play') 
     button("QUIT",550,450,100,50,red,bleu,'Quit') 



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



def game_loop(): 
    global pause 
    pygame.mixer.music.play(-1) 

    x_change=0 
    x=(width*0.45) 
    y=(height*0.8) 
    tx=random.randrange(0,width) 
    ty=-100 
    thing_startx=random.randrange(0,width) 
    thing_starty=-100 
    thing_speed=7 
    thingw=60 
    thingh=60 
    dodge=0 
    gameExit= False 


    while not gameExit: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

      if event.type== pygame.KEYDOWN: 
       if event.key == pygame.K_LEFT: 
        x_change = -5 
       elif event.key == pygame.K_RIGHT: 
        x_change = 5 
       if event.key==pygame.K_p: 
        pause=True 
        paused() 

      if event.type == pygame.KEYUP: 
       if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 
        x_change = 0 



     gameDisplay.fill(white) 
     gameDisplay.blit(backImg,(0,0)) 
     truck(tx,ty) 
     ty+=thing_speed 
     # things(thing_startx,thing_starty,thingw,thingh,red) 
     # thing_starty +=thing_speed 
     car(x,y) 
     dodged(dodge) 
     x += x_change 

     if x > width - carWidth or x < 0: 
      crash() 

     if ty > height: 
      ty = 0 - 100 
      tx = random.randrange(0, width) 
      dodge+=1 


     if y < ty+100: 
      if x > tx and x < tx + 100 or x + carWidth>tx and x + carWidth < tx+100: 
       crash() 


     pygame.display.update() 
     clock.tick(60) 

game_intro() 
game_loop() 
pygame.quit() 
quit() 
+0

Juste quelques remarques générales sur votre code depuis que vous êtes nouveau en programmation: Vous devriez essayer de rendre votre code facile à comprendre. Dans ce cas, cela pourrait signifier copier les fonctions dans un [module] séparé (https://docs.python.org/2/tutorial/modules.html). Ou encore mieux apprendre [comment utiliser les classes] (https://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes) et trouver des fonctionnalités ailleurs. Cela rendra votre futur travail beaucoup plus facile que votre code commence à croître. – Nyps

Répondre

2

Vous appelez entre fonctions méthodes et c'est très mauvais!

réponse possible:

Pygame - RuntimeError: maximum recursion depth exceeded while calling a Python object

Bonne chance!

+1

Je reformulerais la réponse. Le problème est que la fonction 'truck' récursive, c'est-à-dire qu'elle s'appelle * elle-même, et elle s'appelle elle-même jusqu'à ce que la limite de récursivité de Python (de 1000 récursions) soit dépassée. La récursivité n'est pas mauvaise par défaut et peut être très utile, mais une fonction ne peut pas se répéter indéfiniment. – skrx

0

Le RecursionError est provoqué par la fonction truck qui s'appelle elle-même jusqu'à ce que la limite de récursivité de Python soit dépassée. En outre, la surface/image truck et la fonction truck ne doivent pas avoir le même nom (la ligne def truck(tx, ty): remplace la variable image).

Il me semble que vous vouliez juste blit la surface truck dans cette fonction, alors je suggère de le renommer en blit_truck et fixer le code à l'intérieur:

def blit_truck(tx,ty): 
    gameDisplay.blit(truck, (tx, ty)) 
+0

merci pour cette remarque! Je vais le garder à l'esprit – Venom

0

Merci les gars, en fait, l'erreur était quelque chose de stupide, il me manquait une virgule, en gameDisplay.blit(truck , (tx,ty)), à la place j'ai écrit gameDisplay.blit(truck(tx,ty)), maintenant ça marche. merci encore.