Guest User

Untitled

a guest
Feb 26th, 2025
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.20 KB | Gaming | 0 0
  1. import pygame
  2. import random
  3. import time
  4. import math
  5.  
  6. pygame.init()
  7.  
  8. # Configuration de la fenêtre de jeu
  9. window_width = 800
  10. window_height = 600
  11. window = pygame.display.set_mode((window_width, window_height))
  12. pygame.display.set_caption("HFR Pac-Man Snake")
  13.  
  14. # Couleurs
  15. BLACK = (0, 0, 0)
  16. WHITE = (255, 255, 255)
  17. RED = (255, 0, 0)
  18. PINK = (255, 192, 203)
  19. CYAN = (0, 255, 255)
  20. ORANGE = (255, 165, 0)
  21. GREEN = (0, 255, 0)
  22. YELLOW = (255, 255, 0)
  23. BLUE = (0, 0, 255)
  24. WALL_COLOR = (33, 33, 222)
  25. FRUIT_COLOR = (255, 0, 255)  # Magenta pour les fruits spéciaux
  26.  
  27. # Paramètres du jeu
  28. block_size = 20
  29. pacman_speed = 5
  30. ghost_speed = 3
  31.  
  32. # Initialisation de l'horloge
  33. clock = pygame.time.Clock()
  34.  
  35. # Police pour l'affichage du score
  36. font = pygame.font.SysFont(None, 50)
  37.  
  38. # Création de la grille de jeu avec des murs
  39. def create_maze():
  40.     maze = []
  41.     # Créer une bordure autour du jeu
  42.     for y in range(0, window_height // block_size):
  43.         row = []
  44.         for x in range(0, window_width // block_size):
  45.             # Bordures
  46.             if (x == 0 or x == window_width // block_size - 1 or
  47.                 y == 0 or y == window_height // block_size - 1):
  48.                 row.append(1)  # 1 représente un mur
  49.             # Quelques murs intérieurs
  50.             elif (x % 8 == 4 and y % 6 == 3 and
  51.                   x > 3 and x < window_width // block_size - 4 and
  52.                   y > 3 and y < window_height // block_size - 4):
  53.                 # Créer des blocs de murs
  54.                 row.append(1)
  55.             else:
  56.                 row.append(0)  # 0 représente un espace vide
  57.         maze.append(row)
  58.     return maze
  59.  
  60. # Dessiner les murs
  61. def draw_maze(maze):
  62.     for y in range(len(maze)):
  63.         for x in range(len(maze[y])):
  64.             if maze[y][x] == 1:
  65.                 pygame.draw.rect(window, WALL_COLOR,
  66.                                 [x * block_size, y * block_size, block_size, block_size])
  67.  
  68. # Dessiner un segment de Pac-Man (pour la queue)
  69. def draw_pacman_segment(x, y, is_head=False, direction="RIGHT"):
  70.     if is_head:
  71.         # Tête de Pac-Man avec bouche
  72.         mouth_angle = 0
  73.         if direction == "RIGHT":
  74.             mouth_angle = 0
  75.         elif direction == "LEFT":
  76.             mouth_angle = 180
  77.         elif direction == "UP":
  78.             mouth_angle = 90
  79.         elif direction == "DOWN":
  80.             mouth_angle = 270
  81.        
  82.         # Animation de la bouche
  83.         mouth_open = 45 * (1 + math.sin(pygame.time.get_ticks() / 100))
  84.        
  85.         # Dessiner Pac-Man avec bouche
  86.         pygame.draw.circle(window, YELLOW, (int(x + block_size/2), int(y + block_size/2)), block_size/2)
  87.         pygame.draw.polygon(window, BLACK, [
  88.             (x + block_size/2, y + block_size/2),
  89.             (x + block_size/2 + math.cos(math.radians(mouth_angle - mouth_open)) * block_size/2,
  90.              y + block_size/2 - math.sin(math.radians(mouth_angle - mouth_open)) * block_size/2),
  91.             (x + block_size/2 + math.cos(math.radians(mouth_angle + mouth_open)) * block_size/2,
  92.              y + block_size/2 - math.sin(math.radians(mouth_angle + mouth_open)) * block_size/2)
  93.         ])
  94.     else:
  95.         # Corps du serpent (cercles jaunes)
  96.         pygame.draw.circle(window, YELLOW, (int(x + block_size/2), int(y + block_size/2)), block_size/2)
  97.  
  98. # Dessiner les fantômes
  99. def draw_ghost(x, y, color, frightened=False):
  100.     ghost_color = BLUE if frightened else color
  101.    
  102.     # Corps du fantôme
  103.     pygame.draw.circle(window, ghost_color, (int(x + block_size/2), int(y + block_size/2)), block_size/2)
  104.     pygame.draw.rect(window, ghost_color, [x, y + block_size/2, block_size, block_size/2])
  105.    
  106.     # Yeux (blancs en mode normal, effrayés en mode frightened)
  107.     if frightened:
  108.         # Yeux effrayés (blancs avec pupilles)
  109.         eye_radius = block_size/6
  110.         pygame.draw.circle(window, WHITE, (int(x + block_size/3), int(y + block_size/2)), eye_radius)
  111.         pygame.draw.circle(window, WHITE, (int(x + 2*block_size/3), int(y + block_size/2)), eye_radius)
  112.        
  113.         # Bouche effrayée
  114.         pygame.draw.line(window, WHITE,
  115.                         (x + block_size/4, y + 3*block_size/4),
  116.                         (x + 3*block_size/4, y + 3*block_size/4),
  117.                         2)
  118.     else:
  119.         # Yeux normaux
  120.         eye_radius = block_size/6
  121.         pygame.draw.circle(window, WHITE, (int(x + block_size/3), int(y + block_size/2)), eye_radius)
  122.         pygame.draw.circle(window, WHITE, (int(x + 2*block_size/3), int(y + block_size/2)), eye_radius)
  123.        
  124.         # Pupilles
  125.         pupil_radius = eye_radius/2
  126.         pygame.draw.circle(window, BLACK, (int(x + block_size/3), int(y + block_size/2)), pupil_radius)
  127.         pygame.draw.circle(window, BLACK, (int(x + 2*block_size/3), int(y + block_size/2)), pupil_radius)
  128.    
  129.     # Base ondulée
  130.     wave_height = block_size/6
  131.     for i in range(4):
  132.         pygame.draw.circle(window, ghost_color,
  133.                           (int(x + (i+0.5)*block_size/4), int(y + block_size)),
  134.                           wave_height)
  135.  
  136. # Afficher un message
  137. def message(msg, color):
  138.     mesg = font.render(msg, True, color)
  139.     window.blit(mesg, [window_width/6, window_height/3])
  140.  
  141. # Vérifier si une position est valide (pas de collision avec les murs)
  142. def is_valid_position(maze, x, y):
  143.     # Convertir les coordonnées en indices de grille
  144.     grid_x = int(x / block_size)
  145.     grid_y = int(y / block_size)
  146.    
  147.     # Vérifier si les indices sont dans les limites
  148.     if (grid_x < 0 or grid_x >= len(maze[0]) or
  149.         grid_y < 0 or grid_y >= len(maze)):
  150.         return False
  151.    
  152.     # Vérifier s'il y a un mur à cette position
  153.     return maze[grid_y][grid_x] == 0
  154.  
  155. # Placer de la nourriture à des positions valides
  156. def place_food(maze, count=30):
  157.     food_list = []
  158.     while len(food_list) < count:
  159.         x = round(random.randrange(block_size, window_width - block_size*2) / block_size) * block_size
  160.         y = round(random.randrange(block_size, window_height - block_size*2) / block_size) * block_size
  161.         if is_valid_position(maze, x, y):
  162.             if [x, y] not in food_list:
  163.                 food_list.append([x, y])
  164.     return food_list
  165.  
  166. # Placer des fruits spéciaux
  167. def place_fruits(maze, count=4):
  168.     fruits = []
  169.     while len(fruits) < count:
  170.         x = round(random.randrange(block_size, window_width - block_size*2) / block_size) * block_size
  171.         y = round(random.randrange(block_size, window_height - block_size*2) / block_size) * block_size
  172.         if is_valid_position(maze, x, y):
  173.             if [x, y] not in fruits:
  174.                 fruits.append([x, y])
  175.     return fruits
  176.  
  177. # Fonction principale du jeu
  178. def gameLoop():
  179.     game_over = False
  180.     game_close = False
  181.    
  182.     # Position initiale de Pac-Man
  183.     pacman_x = 2 * block_size
  184.     pacman_y = 2 * block_size
  185.     pacman_x_change = 0
  186.     pacman_y_change = 0
  187.     pacman_direction = "RIGHT"
  188.    
  189.     # Liste des segments de Pac-Man (comme pour Snake)
  190.     pacman_segments = []
  191.     pacman_length = 1
  192.    
  193.     # Créer le labyrinthe
  194.     maze = create_maze()
  195.    
  196.     # Créer les fantômes
  197.     ghosts = []
  198.     ghost_colors = [RED, PINK, CYAN, ORANGE]
  199.     for i in range(4):
  200.         ghost_x = window_width - 4 * block_size
  201.         ghost_y = window_height - 4 * block_size
  202.         ghosts.append({
  203.             'x': ghost_x,
  204.             'y': ghost_y,
  205.             'color': ghost_colors[i],
  206.             'direction': random.choice(["UP", "DOWN", "LEFT", "RIGHT"]),
  207.             'frightened': False,
  208.             'alive': True
  209.         })
  210.    
  211.     # Placer la nourriture et les fruits
  212.     food_list = place_food(maze)
  213.     fruits = place_fruits(maze)
  214.     score = 0
  215.    
  216.     # Timer pour le mode "frightened" des fantômes
  217.     frightened_time = 0
  218.     frightened_duration = 10000  # 10 secondes
  219.    
  220.     while not game_over:
  221.         while game_close:
  222.             window.fill(BLACK)
  223.             message("Game Over! Q-Quitter ou C-Rejouer", RED)
  224.             pygame.display.update()
  225.            
  226.             for event in pygame.event.get():
  227.                 if event.type == pygame.KEYDOWN:
  228.                     if event.key == pygame.K_q:
  229.                         game_over = True
  230.                         game_close = False
  231.                     if event.key == pygame.K_c:
  232.                         gameLoop()
  233.        
  234.         # Gestion des événements
  235.         for event in pygame.event.get():
  236.             if event.type == pygame.QUIT:
  237.                 game_over = True
  238.             if event.type == pygame.KEYDOWN:
  239.                 if event.key == pygame.K_LEFT:
  240.                     pacman_x_change = -pacman_speed
  241.                     pacman_y_change = 0
  242.                     pacman_direction = "LEFT"
  243.                 elif event.key == pygame.K_RIGHT:
  244.                     pacman_x_change = pacman_speed
  245.                     pacman_y_change = 0
  246.                     pacman_direction = "RIGHT"
  247.                 elif event.key == pygame.K_UP:
  248.                     pacman_y_change = -pacman_speed
  249.                     pacman_x_change = 0
  250.                     pacman_direction = "UP"
  251.                 elif event.key == pygame.K_DOWN:
  252.                     pacman_y_change = pacman_speed
  253.                     pacman_x_change = 0
  254.                     pacman_direction = "DOWN"
  255.        
  256.         # Mise à jour de la position de Pac-Man
  257.         new_pacman_x = pacman_x + pacman_x_change
  258.         new_pacman_y = pacman_y + pacman_y_change
  259.        
  260.         # Vérifier si la nouvelle position est valide
  261.         if is_valid_position(maze, new_pacman_x, new_pacman_y):
  262.             pacman_x = new_pacman_x
  263.             pacman_y = new_pacman_y
  264.        
  265.         # Vérifier la collision avec la queue de Pac-Man
  266.         for segment in pacman_segments[:-1]:  # Exclure la tête
  267.             if pacman_x == segment[0] and pacman_y == segment[1]:
  268.                 game_close = True
  269.        
  270.         # Mettre à jour la liste des segments de Pac-Man
  271.         pacman_head = []
  272.         pacman_head.append(pacman_x)
  273.         pacman_head.append(pacman_y)
  274.         pacman_segments.append(pacman_head)
  275.        
  276.         # Supprimer l'ancien segment si nécessaire
  277.         if len(pacman_segments) > pacman_length:
  278.             del pacman_segments[0]
  279.        
  280.         # Mode frightened timer
  281.         current_time = pygame.time.get_ticks()
  282.         if frightened_time > 0 and current_time - frightened_time > frightened_duration:
  283.             # Fin du mode frightened
  284.             frightened_time = 0
  285.             for ghost in ghosts:
  286.                 ghost['frightened'] = False
  287.        
  288.         # Mise à jour des positions des fantômes
  289.         for ghost in ghosts:
  290.             if ghost['alive']:  # Ignorer les fantômes mangés
  291.                 # Changer de direction aléatoirement ou quand un mur est rencontré
  292.                 if random.random() < 0.02:  # 2% de chance de changer de direction
  293.                     ghost['direction'] = random.choice(["UP", "DOWN", "LEFT", "RIGHT"])
  294.                
  295.                 # Calculer la nouvelle position
  296.                 new_ghost_x, new_ghost_y = ghost['x'], ghost['y']
  297.                
  298.                 # Mouvement plus lent pour les fantômes effrayés
  299.                 current_speed = ghost_speed / 2 if ghost['frightened'] else ghost_speed
  300.                
  301.                 if ghost['direction'] == "RIGHT":
  302.                     new_ghost_x += current_speed
  303.                 elif ghost['direction'] == "LEFT":
  304.                     new_ghost_x -= current_speed
  305.                 elif ghost['direction'] == "UP":
  306.                     new_ghost_y -= current_speed
  307.                 elif ghost['direction'] == "DOWN":
  308.                     new_ghost_y += current_speed
  309.                
  310.                 # Vérifier si la nouvelle position est valide
  311.                 if is_valid_position(maze, new_ghost_x, new_ghost_y):
  312.                     ghost['x'], ghost['y'] = new_ghost_x, new_ghost_y
  313.                 else:
  314.                     # Si la position n'est pas valide, changer de direction
  315.                     ghost['direction'] = random.choice(["UP", "DOWN", "LEFT", "RIGHT"])
  316.        
  317.         # Vérifier les collisions avec les fantômes
  318.         for ghost in ghosts:
  319.             if ghost['alive'] and (abs(pacman_x - ghost['x']) < block_size and
  320.                                 abs(pacman_y - ghost['y']) < block_size):
  321.                 if ghost['frightened']:
  322.                     # Manger le fantôme
  323.                     ghost['alive'] = False
  324.                     score += 200
  325.                 else:
  326.                     # Game over si collision avec un fantôme non effrayé
  327.                     game_close = True
  328.        
  329.         # Vérifier la consommation de nourriture
  330.         for food in food_list[:]:
  331.             if (abs(pacman_x - food[0]) < block_size and
  332.                 abs(pacman_y - food[1]) < block_size):
  333.                 food_list.remove(food)
  334.                 score += 10
  335.                 pacman_length += 1
  336.        
  337.         # Vérifier la consommation de fruits
  338.         for fruit in fruits[:]:
  339.             if (abs(pacman_x - fruit[0]) < block_size and
  340.                 abs(pacman_y - fruit[1]) < block_size):
  341.                 fruits.remove(fruit)
  342.                 score += 50
  343.                 # Activer le mode frightened pour tous les fantômes
  344.                 frightened_time = pygame.time.get_ticks()
  345.                 for ghost in ghosts:
  346.                     if ghost['alive']:
  347.                         ghost['frightened'] = True
  348.        
  349.         # Régénérer les fruits s'ils sont tous mangés
  350.         if len(fruits) == 0 and random.random() < 0.005:  # 0.5% de chance de réapparition
  351.             fruits = place_fruits(maze, count=2)
  352.        
  353.         # Si toute la nourriture est mangée, gagner la partie
  354.         if len(food_list) == 0:
  355.             window.fill(BLACK)
  356.             message("Vous avez gagné!", GREEN)
  357.             pygame.display.update()
  358.             time.sleep(3)
  359.             game_close = True
  360.        
  361.         # Dessiner
  362.         window.fill(BLACK)
  363.         draw_maze(maze)
  364.        
  365.         # Dessiner la nourriture
  366.         for food in food_list:
  367.             pygame.draw.circle(window, WHITE,
  368.                               (int(food[0] + block_size/2), int(food[1] + block_size/2)),
  369.                               block_size/5)
  370.        
  371.         # Dessiner les fruits spéciaux
  372.         for fruit in fruits:
  373.             pygame.draw.circle(window, FRUIT_COLOR,
  374.                               (int(fruit[0] + block_size/2), int(fruit[1] + block_size/2)),
  375.                               block_size/2)
  376.        
  377.         # Dessiner Pac-Man (queue snake)
  378.         for i, segment in enumerate(pacman_segments):
  379.             is_head = (i == len(pacman_segments) - 1)
  380.             draw_pacman_segment(segment[0], segment[1], is_head, pacman_direction)
  381.        
  382.         # Dessiner les fantômes
  383.         for ghost in ghosts:
  384.             if ghost['alive']:
  385.                 draw_ghost(ghost['x'], ghost['y'], ghost['color'], ghost['frightened'])
  386.        
  387.         # Afficher le score
  388.         score_text = font.render(f"Score: {score}", True, WHITE)
  389.         window.blit(score_text, [10, 10])
  390.        
  391.         pygame.display.update()
  392.         clock.tick(30)
  393.    
  394.     pygame.quit()
  395.     quit()
  396.  
  397. # Démarrer le jeu
  398. gameLoop()
Advertisement
Add Comment
Please, Sign In to add comment