Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
2480 connectés 

  FORUM HardWare.fr
  Programmation
  Python

  Python

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

Python

n°2257779
anUSB
Posté le 10-05-2015 à 12:43:14  profilanswer
 

Bonjour ! érant sur internet et débutant en programmation je voulais commencer par creer mon propre snake sur edupython dans le cadre de ma spécialite en terminale seulment voila
je ne m'y connait pas trop et c'est plutot compliqué d'improviser le code source c'est pourquoi j'en ai piqué un sur internet pour essayer de le comprendre et accesoirement  
le modifier   :)  mais certaines parties me sont incomprehensibles et c est pourqoui je viens ici demander quelques explications :??:  
je le mets ci dessous , les parties non commentées sont celles qui m'echappent  ! merci beaucoup d'avance pour votre aide  :love:  
 

Code :
  1. # Créé par poirrieh, le 19/03/2015 en Python 3.2
  2. import random
  3. import pygame
  4. import sys
  5. from pygame.locals import *
  6. Snakespeed= 30
  7.  
  8. Window_Width= 800
  9. Window_Height= 500
  10. Cell_Size = 20 #largeur et la hauteur des cellules
  11.  
  12.  
  13. Cell_W= int(Window_Width / Cell_Size) # largeurs des céllules
  14. Cell_H= int(Window_Height / Cell_Size) #Hauteur des cellules
  15.  
  16.  
  17. fenetre = pygame.display.set_mode((640, 480)) #defini taille de la fenetre
  18. fond = pygame.image.load("imagefd.jpg" ).convert() #charge l image
  19. fenetre.blit(fond, (0,0)) # applique l'image
  20.  
  21.  
  22. pygame.mixer.init() #initialisation du module mixer pour python
  23. sonpomme = pygame.mixer.Sound('AppleSon.wav') #définition du fichier
  24. pygame.mixer.music.load("musicfd.mp3" ) #charge fichier audio
  25.  
  26. White= (255,255,255)
  27. Black= (0,0,0)
  28. Red= (255,0,0) # Définition des couleurs des éléments du programme.
  29. Green= (0,255,0)
  30. DARKGreen= (0,155,0)
  31. DARKGRAY= (40,40,40)
  32. YELLOW= (255,255,0)
  33. Red_DARK= (150,0,0)
  34. BLUE= (0,0,255)
  35. BLUE_DARK= (0,0,150)
  36.  
  37. UP = 'up'
  38. DOWN = 'down'      # Définit les touches du clavier.
  39. LEFT = 'left'
  40. RIGHT = 'right'
  41.  
  42. HEAD = 0 #: indice de la tête du serpent
  43.  
  44. def main():
  45.    global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
  46.    pygame.init()
  47.    SnakespeedCLOCK = pygame.time.Clock()
  48.    DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
  49.    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
  50.    pygame.display.set_caption('Snake')
  51.    showStartScreen()
  52.    while True:
  53.        pygame.mixer.music.play() #joue musique de fond
  54.        runGame()
  55.        showGameOverScreen()
  56. def runGame():
  57.    # Défini un point de départ .
  58.    startx = 18
  59.    starty = 15
  60.    wormCoords = [{'x': startx,     'y': starty},
  61.                  {'x': startx - 1, 'y': starty},
  62.                  {'x': startx - 2, 'y': starty}]
  63.    direction = RIGHT
  64.    apple = getRandomLocation()# Lancer la pomme dans un endroit aléatoire.
  65.    while True: # Boucle principale du jeu
  66.        for event in pygame.event.get(): # Événement boucle de manipulation
  67.            if event.type == QUIT:
  68.                terminate()
  69.            elif event.type == KEYDOWN:
  70.                if (event.key == K_LEFT ) and direction != RIGHT:
  71.                    direction = LEFT
  72.                elif (event.key == K_RIGHT ) and direction != LEFT:
  73.                    direction = RIGHT
  74.                elif (event.key == K_UP ) and direction != DOWN:
  75.                    direction = UP
  76.                elif (event.key == K_DOWN ) and direction != UP:
  77.                    direction = DOWN
  78.  
  79.        # Vérifie si le serpent s'est touché ou s'il a touché le bord
  80.        if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or     wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
  81.  
  82.            pygame.mixer.music.stop() #arrete la musique de fond
  83.            pygame.mixer.Sound("9333.wav" ).play() #joue son défaite
  84.  
  85.            return # Jeu terminé
  86.        for wormBody in wormCoords[1:]:
  87.            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]    ['y']:
  88.  
  89.                pygame.mixer.Sound("9333.wav" ).play() #joue son défaite
  90.                pygame.mixer.music.stop() #arrete la musique de fond
  91.  
  92.                return # Jeu terminé
  93.        # Vérifier si Serpent a mangé une apple
  94.        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
  95.            # Ne pas enlever la queue du segment de ver
  96.            pygame.mixer.Sound("AppleSon.wav" ).play() # joue le son de la pomme mangée
  97.            apple = getRandomLocation() # Établi une nouvelle pomme quelque part
  98.        else:
  99.            del wormCoords[-1] # Retirer la queue du segment de ver
  100.        # Déplacer le ver en ajoutant un segment dans le sens ou il se déplace
  101.        if direction == UP:
  102.            newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
  103.        elif direction == DOWN:
  104.            newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
  105.        elif direction == LEFT:
  106.            newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
  107.        elif direction == RIGHT:
  108.            newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
  109.        wormCoords.insert(0, newHead)
  110.        fenetre.blit(fond, (0,0))
  111.        drawWorm(wormCoords)
  112.        drawApple(apple)
  113.        drawScore(len(wormCoords) - 3)
  114.        pygame.display.update()
  115.        SnakespeedCLOCK.tick(Snakespeed)
  116. def drawPressKeyMsg():
  117.    pressKeySurf = BASICFONT.render('Appuie sur espace pour jouer', True, White)
  118.    pressKeyRect = pressKeySurf.get_rect()
  119.    pressKeyRect.topleft = (Window_Width - 280, Window_Height - 30)
  120.    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
  121. def checkForKeyPress():
  122.    if len(pygame.event.get(QUIT)) > 0:
  123.        terminate()
  124.    keyUpEvents = pygame.event.get(KEYUP)
  125.    if len(keyUpEvents) == 0:
  126.        return None
  127.    if keyUpEvents[0].key == K_ESCAPE:
  128.        terminate()
  129.    return keyUpEvents[0].key
  130. def showStartScreen():
  131.    titleFont = pygame.font.Font('freesansbold.ttf', 200)
  132.    titleSurf1 = titleFont.render('SNAKE!', True, White, BLUE_DARK)
  133.    degrees1 = 0
  134.    degrees2 = 0
  135.    while True:
  136.        fenetre.blit(fond, (0,0))
  137.        rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
  138.        rotatedRect1 = rotatedSurf1.get_rect()
  139.        rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
  140.        DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
  141.        drawPressKeyMsg()
  142.        if checkForKeyPress():
  143.            pygame.event.get() # File d'attente d'événement clear
  144.            return
  145.        pygame.display.update()
  146.        SnakespeedCLOCK.tick(Snakespeed)
  147.        degrees1 += 3 # Tournent de 3 degrés chaque image
  148.        degrees2 += 7 # Tournent de 7 degrés chaque image
  149. def terminate():
  150.    pygame.quit()
  151.    sys.exit()
  152. def getRandomLocation():
  153.    return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
  154. def showGameOverScreen():
  155.    gameOverFont = pygame.font.Font('freesansbold.ttf', 200)
  156.    gameSurf = gameOverFont.render('Perdu', True, White)
  157.    gameRect = gameSurf.get_rect()
  158.    gameRect.midtop = (400, 150)
  159.    DISPLAYSURF.blit(gameSurf, gameRect)
  160.    drawPressKeyMsg()
  161.    pygame.display.update()
  162.    pygame.time.wait(500)
  163.    checkForKeyPress() # Effacer tous les touches dans la file d'attente de l'événement
  164.    while True:
  165.        if checkForKeyPress():
  166.            pygame.event.get() # File d'attente d'événement clear
  167.            return
  168. def drawScore(score):
  169.    scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
  170.    scoreRect = scoreSurf.get_rect()
  171.    scoreRect.topleft = (Window_Width - 120, 10)
  172.    DISPLAYSURF.blit(scoreSurf, scoreRect)
  173. def drawWorm(wormCoords):
  174.    for coord in wormCoords:
  175.        x = coord['x'] * Cell_Size
  176.        y = coord['y'] * Cell_Size
  177.        wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  178.        pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
  179.        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
  180.        pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
  181. def drawApple(coord):
  182.    x = coord['x'] * Cell_Size
  183.    y = coord['y'] * Cell_Size
  184.    appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  185.    pygame.draw.rect(DISPLAYSURF, Red or Green , appleRect)
  186. if __name__ == '__main__':
  187.    try:
  188.        main()
  189.    except SystemExit:
  190.            pass


 
voila voila !


Message édité par gilou le 10-05-2015 à 14:16:40
mood
Publicité
Posté le 10-05-2015 à 12:43:14  profilanswer
 


Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  Python

  Python

 

Sujets relatifs
[Python] Tetris, besoin d'aide pour élimination d'une ligne complèteProblème de sortie d'une boucle while en PYTHON
Créer un classement en python 2.7programmation score de tennis python pygame
[python] 2048 intelligence artificielleaide pour programme python !
Débutant python dictionnaire sérialisé[Python] Occurence d'une liste
Créer une animation en python[RESOLU (et toute seule en plus)] Python 3.2 Comment utiliser les set?
Plus de sujets relatifs à : Python


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR