Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import random
- import time
- import math
- pygame.init()
- # Configuration de la fenêtre de jeu
- window_width = 800
- window_height = 600
- window = pygame.display.set_mode((window_width, window_height))
- pygame.display.set_caption("HFR Pac-Man Snake")
- # Couleurs
- BLACK = (0, 0, 0)
- WHITE = (255, 255, 255)
- RED = (255, 0, 0)
- PINK = (255, 192, 203)
- CYAN = (0, 255, 255)
- ORANGE = (255, 165, 0)
- GREEN = (0, 255, 0)
- YELLOW = (255, 255, 0)
- BLUE = (0, 0, 255)
- WALL_COLOR = (33, 33, 222)
- FRUIT_COLOR = (255, 0, 255) # Magenta pour les fruits spéciaux
- # Paramètres du jeu
- block_size = 20
- pacman_speed = 5
- ghost_speed = 3
- # Initialisation de l'horloge
- clock = pygame.time.Clock()
- # Police pour l'affichage du score
- font = pygame.font.SysFont(None, 50)
- # Création de la grille de jeu avec des murs
- def create_maze():
- maze = []
- # Créer une bordure autour du jeu
- for y in range(0, window_height // block_size):
- row = []
- for x in range(0, window_width // block_size):
- # Bordures
- if (x == 0 or x == window_width // block_size - 1 or
- y == 0 or y == window_height // block_size - 1):
- row.append(1) # 1 représente un mur
- # Quelques murs intérieurs
- elif (x % 8 == 4 and y % 6 == 3 and
- x > 3 and x < window_width // block_size - 4 and
- y > 3 and y < window_height // block_size - 4):
- # Créer des blocs de murs
- row.append(1)
- else:
- row.append(0) # 0 représente un espace vide
- maze.append(row)
- return maze
- # Dessiner les murs
- def draw_maze(maze):
- for y in range(len(maze)):
- for x in range(len(maze[y])):
- if maze[y][x] == 1:
- pygame.draw.rect(window, WALL_COLOR,
- [x * block_size, y * block_size, block_size, block_size])
- # Dessiner un segment de Pac-Man (pour la queue)
- def draw_pacman_segment(x, y, is_head=False, direction="RIGHT"):
- if is_head:
- # Tête de Pac-Man avec bouche
- mouth_angle = 0
- if direction == "RIGHT":
- mouth_angle = 0
- elif direction == "LEFT":
- mouth_angle = 180
- elif direction == "UP":
- mouth_angle = 90
- elif direction == "DOWN":
- mouth_angle = 270
- # Animation de la bouche
- mouth_open = 45 * (1 + math.sin(pygame.time.get_ticks() / 100))
- # Dessiner Pac-Man avec bouche
- pygame.draw.circle(window, YELLOW, (int(x + block_size/2), int(y + block_size/2)), block_size/2)
- pygame.draw.polygon(window, BLACK, [
- (x + block_size/2, y + block_size/2),
- (x + block_size/2 + math.cos(math.radians(mouth_angle - mouth_open)) * block_size/2,
- y + block_size/2 - math.sin(math.radians(mouth_angle - mouth_open)) * block_size/2),
- (x + block_size/2 + math.cos(math.radians(mouth_angle + mouth_open)) * block_size/2,
- y + block_size/2 - math.sin(math.radians(mouth_angle + mouth_open)) * block_size/2)
- ])
- else:
- # Corps du serpent (cercles jaunes)
- pygame.draw.circle(window, YELLOW, (int(x + block_size/2), int(y + block_size/2)), block_size/2)
- # Dessiner les fantômes
- def draw_ghost(x, y, color, frightened=False):
- ghost_color = BLUE if frightened else color
- # Corps du fantôme
- pygame.draw.circle(window, ghost_color, (int(x + block_size/2), int(y + block_size/2)), block_size/2)
- pygame.draw.rect(window, ghost_color, [x, y + block_size/2, block_size, block_size/2])
- # Yeux (blancs en mode normal, effrayés en mode frightened)
- if frightened:
- # Yeux effrayés (blancs avec pupilles)
- eye_radius = block_size/6
- pygame.draw.circle(window, WHITE, (int(x + block_size/3), int(y + block_size/2)), eye_radius)
- pygame.draw.circle(window, WHITE, (int(x + 2*block_size/3), int(y + block_size/2)), eye_radius)
- # Bouche effrayée
- pygame.draw.line(window, WHITE,
- (x + block_size/4, y + 3*block_size/4),
- (x + 3*block_size/4, y + 3*block_size/4),
- 2)
- else:
- # Yeux normaux
- eye_radius = block_size/6
- pygame.draw.circle(window, WHITE, (int(x + block_size/3), int(y + block_size/2)), eye_radius)
- pygame.draw.circle(window, WHITE, (int(x + 2*block_size/3), int(y + block_size/2)), eye_radius)
- # Pupilles
- pupil_radius = eye_radius/2
- pygame.draw.circle(window, BLACK, (int(x + block_size/3), int(y + block_size/2)), pupil_radius)
- pygame.draw.circle(window, BLACK, (int(x + 2*block_size/3), int(y + block_size/2)), pupil_radius)
- # Base ondulée
- wave_height = block_size/6
- for i in range(4):
- pygame.draw.circle(window, ghost_color,
- (int(x + (i+0.5)*block_size/4), int(y + block_size)),
- wave_height)
- # Afficher un message
- def message(msg, color):
- mesg = font.render(msg, True, color)
- window.blit(mesg, [window_width/6, window_height/3])
- # Vérifier si une position est valide (pas de collision avec les murs)
- def is_valid_position(maze, x, y):
- # Convertir les coordonnées en indices de grille
- grid_x = int(x / block_size)
- grid_y = int(y / block_size)
- # Vérifier si les indices sont dans les limites
- if (grid_x < 0 or grid_x >= len(maze[0]) or
- grid_y < 0 or grid_y >= len(maze)):
- return False
- # Vérifier s'il y a un mur à cette position
- return maze[grid_y][grid_x] == 0
- # Placer de la nourriture à des positions valides
- def place_food(maze, count=30):
- food_list = []
- while len(food_list) < count:
- x = round(random.randrange(block_size, window_width - block_size*2) / block_size) * block_size
- y = round(random.randrange(block_size, window_height - block_size*2) / block_size) * block_size
- if is_valid_position(maze, x, y):
- if [x, y] not in food_list:
- food_list.append([x, y])
- return food_list
- # Placer des fruits spéciaux
- def place_fruits(maze, count=4):
- fruits = []
- while len(fruits) < count:
- x = round(random.randrange(block_size, window_width - block_size*2) / block_size) * block_size
- y = round(random.randrange(block_size, window_height - block_size*2) / block_size) * block_size
- if is_valid_position(maze, x, y):
- if [x, y] not in fruits:
- fruits.append([x, y])
- return fruits
- # Fonction principale du jeu
- def gameLoop():
- game_over = False
- game_close = False
- # Position initiale de Pac-Man
- pacman_x = 2 * block_size
- pacman_y = 2 * block_size
- pacman_x_change = 0
- pacman_y_change = 0
- pacman_direction = "RIGHT"
- # Liste des segments de Pac-Man (comme pour Snake)
- pacman_segments = []
- pacman_length = 1
- # Créer le labyrinthe
- maze = create_maze()
- # Créer les fantômes
- ghosts = []
- ghost_colors = [RED, PINK, CYAN, ORANGE]
- for i in range(4):
- ghost_x = window_width - 4 * block_size
- ghost_y = window_height - 4 * block_size
- ghosts.append({
- 'x': ghost_x,
- 'y': ghost_y,
- 'color': ghost_colors[i],
- 'direction': random.choice(["UP", "DOWN", "LEFT", "RIGHT"]),
- 'frightened': False,
- 'alive': True
- })
- # Placer la nourriture et les fruits
- food_list = place_food(maze)
- fruits = place_fruits(maze)
- score = 0
- # Timer pour le mode "frightened" des fantômes
- frightened_time = 0
- frightened_duration = 10000 # 10 secondes
- while not game_over:
- while game_close:
- window.fill(BLACK)
- message("Game Over! Q-Quitter ou C-Rejouer", RED)
- pygame.display.update()
- for event in pygame.event.get():
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_q:
- game_over = True
- game_close = False
- if event.key == pygame.K_c:
- gameLoop()
- # Gestion des événements
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- game_over = True
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_LEFT:
- pacman_x_change = -pacman_speed
- pacman_y_change = 0
- pacman_direction = "LEFT"
- elif event.key == pygame.K_RIGHT:
- pacman_x_change = pacman_speed
- pacman_y_change = 0
- pacman_direction = "RIGHT"
- elif event.key == pygame.K_UP:
- pacman_y_change = -pacman_speed
- pacman_x_change = 0
- pacman_direction = "UP"
- elif event.key == pygame.K_DOWN:
- pacman_y_change = pacman_speed
- pacman_x_change = 0
- pacman_direction = "DOWN"
- # Mise à jour de la position de Pac-Man
- new_pacman_x = pacman_x + pacman_x_change
- new_pacman_y = pacman_y + pacman_y_change
- # Vérifier si la nouvelle position est valide
- if is_valid_position(maze, new_pacman_x, new_pacman_y):
- pacman_x = new_pacman_x
- pacman_y = new_pacman_y
- # Vérifier la collision avec la queue de Pac-Man
- for segment in pacman_segments[:-1]: # Exclure la tête
- if pacman_x == segment[0] and pacman_y == segment[1]:
- game_close = True
- # Mettre à jour la liste des segments de Pac-Man
- pacman_head = []
- pacman_head.append(pacman_x)
- pacman_head.append(pacman_y)
- pacman_segments.append(pacman_head)
- # Supprimer l'ancien segment si nécessaire
- if len(pacman_segments) > pacman_length:
- del pacman_segments[0]
- # Mode frightened timer
- current_time = pygame.time.get_ticks()
- if frightened_time > 0 and current_time - frightened_time > frightened_duration:
- # Fin du mode frightened
- frightened_time = 0
- for ghost in ghosts:
- ghost['frightened'] = False
- # Mise à jour des positions des fantômes
- for ghost in ghosts:
- if ghost['alive']: # Ignorer les fantômes mangés
- # Changer de direction aléatoirement ou quand un mur est rencontré
- if random.random() < 0.02: # 2% de chance de changer de direction
- ghost['direction'] = random.choice(["UP", "DOWN", "LEFT", "RIGHT"])
- # Calculer la nouvelle position
- new_ghost_x, new_ghost_y = ghost['x'], ghost['y']
- # Mouvement plus lent pour les fantômes effrayés
- current_speed = ghost_speed / 2 if ghost['frightened'] else ghost_speed
- if ghost['direction'] == "RIGHT":
- new_ghost_x += current_speed
- elif ghost['direction'] == "LEFT":
- new_ghost_x -= current_speed
- elif ghost['direction'] == "UP":
- new_ghost_y -= current_speed
- elif ghost['direction'] == "DOWN":
- new_ghost_y += current_speed
- # Vérifier si la nouvelle position est valide
- if is_valid_position(maze, new_ghost_x, new_ghost_y):
- ghost['x'], ghost['y'] = new_ghost_x, new_ghost_y
- else:
- # Si la position n'est pas valide, changer de direction
- ghost['direction'] = random.choice(["UP", "DOWN", "LEFT", "RIGHT"])
- # Vérifier les collisions avec les fantômes
- for ghost in ghosts:
- if ghost['alive'] and (abs(pacman_x - ghost['x']) < block_size and
- abs(pacman_y - ghost['y']) < block_size):
- if ghost['frightened']:
- # Manger le fantôme
- ghost['alive'] = False
- score += 200
- else:
- # Game over si collision avec un fantôme non effrayé
- game_close = True
- # Vérifier la consommation de nourriture
- for food in food_list[:]:
- if (abs(pacman_x - food[0]) < block_size and
- abs(pacman_y - food[1]) < block_size):
- food_list.remove(food)
- score += 10
- pacman_length += 1
- # Vérifier la consommation de fruits
- for fruit in fruits[:]:
- if (abs(pacman_x - fruit[0]) < block_size and
- abs(pacman_y - fruit[1]) < block_size):
- fruits.remove(fruit)
- score += 50
- # Activer le mode frightened pour tous les fantômes
- frightened_time = pygame.time.get_ticks()
- for ghost in ghosts:
- if ghost['alive']:
- ghost['frightened'] = True
- # Régénérer les fruits s'ils sont tous mangés
- if len(fruits) == 0 and random.random() < 0.005: # 0.5% de chance de réapparition
- fruits = place_fruits(maze, count=2)
- # Si toute la nourriture est mangée, gagner la partie
- if len(food_list) == 0:
- window.fill(BLACK)
- message("Vous avez gagné!", GREEN)
- pygame.display.update()
- time.sleep(3)
- game_close = True
- # Dessiner
- window.fill(BLACK)
- draw_maze(maze)
- # Dessiner la nourriture
- for food in food_list:
- pygame.draw.circle(window, WHITE,
- (int(food[0] + block_size/2), int(food[1] + block_size/2)),
- block_size/5)
- # Dessiner les fruits spéciaux
- for fruit in fruits:
- pygame.draw.circle(window, FRUIT_COLOR,
- (int(fruit[0] + block_size/2), int(fruit[1] + block_size/2)),
- block_size/2)
- # Dessiner Pac-Man (queue snake)
- for i, segment in enumerate(pacman_segments):
- is_head = (i == len(pacman_segments) - 1)
- draw_pacman_segment(segment[0], segment[1], is_head, pacman_direction)
- # Dessiner les fantômes
- for ghost in ghosts:
- if ghost['alive']:
- draw_ghost(ghost['x'], ghost['y'], ghost['color'], ghost['frightened'])
- # Afficher le score
- score_text = font.render(f"Score: {score}", True, WHITE)
- window.blit(score_text, [10, 10])
- pygame.display.update()
- clock.tick(30)
- pygame.quit()
- quit()
- # Démarrer le jeu
- gameLoop()
Advertisement
Add Comment
Please, Sign In to add comment