# Créé par poirrieh, le 19/03/2015 en Python 3.2
import random
import pygame
import sys
from pygame.locals import *
Snakespeed= 30
Window_Width= 800
Window_Height= 500
Cell_Size = 20 #largeur et la hauteur des cellules
Cell_W= int(Window_Width / Cell_Size) # largeurs des céllules
Cell_H= int(Window_Height / Cell_Size) #Hauteur des cellules
fenetre = pygame.display.set_mode((640, 480)) #defini taille de la fenetre
fond = pygame.image.load("imagefd.jpg" ).convert() #charge l image
fenetre.blit(fond, (0,0)) # applique l'image
pygame.mixer.init() #initialisation du module mixer pour python
sonpomme = pygame.mixer.Sound('AppleSon.wav') #définition du fichier
pygame.mixer.music.load("musicfd.mp3" ) #charge fichier audio
White= (255,255,255)
Black= (0,0,0)
Red= (255,0,0) # Définition des couleurs des éléments du programme.
Green= (0,255,0)
DARKGreen= (0,155,0)
DARKGRAY= (40,40,40)
YELLOW= (255,255,0)
Red_DARK= (150,0,0)
BLUE= (0,0,255)
BLUE_DARK= (0,0,150)
UP = 'up'
DOWN = 'down' # Définit les touches du clavier.
LEFT = 'left'
RIGHT = 'right'
HEAD = 0 #: indice de la tête du serpent
def main():
global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
pygame.init()
SnakespeedCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Snake')
showStartScreen()
while True:
pygame.mixer.music.play() #joue musique de fond
runGame()
showGameOverScreen()
def runGame():
# Défini un point de départ .
startx = 18
starty = 15
wormCoords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT
apple = getRandomLocation()# Lancer la pomme dans un endroit aléatoire.
while True: # Boucle principale du jeu
for event in pygame.event.get(): # Événement boucle de manipulation
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT ) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT ) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP ) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN ) and direction != UP:
direction = DOWN
# Vérifie si le serpent s'est touché ou s'il a touché le bord
if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
pygame.mixer.music.stop() #arrete la musique de fond
pygame.mixer.Sound("9333.wav" ).play() #joue son défaite
return # Jeu terminé
for wormBody in wormCoords[1:]:
if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD] ['y']:
pygame.mixer.Sound("9333.wav" ).play() #joue son défaite
pygame.mixer.music.stop() #arrete la musique de fond
return # Jeu terminé
# Vérifier si Serpent a mangé une apple
if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
# Ne pas enlever la queue du segment de ver
pygame.mixer.Sound("AppleSon.wav" ).play() # joue le son de la pomme mangée
apple = getRandomLocation() # Établi une nouvelle pomme quelque part
else:
del wormCoords[-1] # Retirer la queue du segment de ver
# Déplacer le ver en ajoutant un segment dans le sens ou il se déplace
if direction == UP:
newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
elif direction == DOWN:
newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
elif direction == LEFT:
newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
elif direction == RIGHT:
newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
wormCoords.insert(0, newHead)
fenetre.blit(fond, (0,0))
drawWorm(wormCoords)
drawApple(apple)
drawScore(len(wormCoords) - 3)
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render('Appuie sur espace pour jouer', True, White)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (Window_Width - 280, Window_Height - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
def checkForKeyPress():
if len(pygame.event.get(QUIT)) > 0:
terminate()
keyUpEvents = pygame.event.get(KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0].key == K_ESCAPE:
terminate()
return keyUpEvents[0].key
def showStartScreen():
titleFont = pygame.font.Font('freesansbold.ttf', 200)
titleSurf1 = titleFont.render('SNAKE!', True, White, BLUE_DARK)
degrees1 = 0
degrees2 = 0
while True:
fenetre.blit(fond, (0,0))
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
rotatedRect1 = rotatedSurf1.get_rect()
rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get() # File d'attente d'événement clear
return
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
degrees1 += 3 # Tournent de 3 degrés chaque image
degrees2 += 7 # Tournent de 7 degrés chaque image
def terminate():
pygame.quit()
sys.exit()
def getRandomLocation():
return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
def showGameOverScreen():
gameOverFont = pygame.font.Font('freesansbold.ttf', 200)
gameSurf = gameOverFont.render('Perdu', True, White)
gameRect = gameSurf.get_rect()
gameRect.midtop = (400, 150)
DISPLAYSURF.blit(gameSurf, gameRect)
drawPressKeyMsg()
pygame.display.update()
pygame.time.wait(500)
checkForKeyPress() # Effacer tous les touches dans la file d'attente de l'événement
while True:
if checkForKeyPress():
pygame.event.get() # File d'attente d'événement clear
return
def drawScore(score):
scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (Window_Width - 120, 10)
DISPLAYSURF.blit(scoreSurf, scoreRect)
def drawWorm(wormCoords):
for coord in wormCoords:
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
def drawApple(coord):
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(DISPLAYSURF, Red or Green , appleRect)
if __name__ == '__main__':
try:
main()
except SystemExit:
pass