Advertisement
Python253

snake_game

May 13th, 2024
853
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.39 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: snake_game.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script implements a simple Snake game using Pygame.
  9.  
  10. Functions:
  11.    - display_text: Displays text on the screen.
  12.    - draw_snake: Draws the snake on the game display.
  13.    - game_over_screen: Displays the game over screen with the final score.
  14.    - draw_gradient_background: Fills the background with a gradient of dark green.
  15.    - game_loop: Main game loop that handles game logic, user input, and rendering.
  16.  
  17. Requirements:
  18.    - Python 3.x
  19.    - Pygame
  20.  
  21. Usage:
  22.    1. Make sure Python and Pygame are installed on your system.
  23.    2. Run the script using Python.
  24.    3. Use the arrow keys to control the snake.
  25.    4. Eat the red food blocks to grow the snake and earn points.
  26.    5. Avoid running into the walls or the snake itself.
  27.    6. Press 'Q' to quit the game at any time.
  28.  
  29. Additional Notes:
  30.    - The snake starts in the center of the screen and moves in the direction specified by the arrow keys.
  31.    - The game ends when the snake collides with the walls or itself.
  32.    - The player's score increases by 10 points each time the snake eats food.
  33.    - The game over screen displays the final score and provides options to play again or quit.
  34.    - The background is filled with a gradient of dark green color.
  35. """
  36.  
  37. import pygame
  38. import random
  39.  
  40. # Initialize Pygame
  41. pygame.init()
  42.  
  43. # Define colors
  44. WHITE = (255, 255, 255)
  45. BLACK = (0, 0, 0)
  46. RED = (255, 0, 0)
  47. GREEN = (0, 128, 0)  # Dark green
  48.  
  49. # Set up the game window
  50. WINDOW_WIDTH = 800
  51. WINDOW_HEIGHT = 600
  52. game_display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
  53. pygame.display.set_caption("Snake Game")
  54.  
  55. # Set up the clock
  56. clock = pygame.time.Clock()
  57.  
  58. # Set up the font
  59. font = pygame.font.SysFont(None, 30)
  60.  
  61. # Define block size and FPS
  62. BLOCK_SIZE = 20
  63. FPS = 10
  64.  
  65. # Define directions
  66. UP = 0
  67. DOWN = 1
  68. LEFT = 2
  69. RIGHT = 3
  70.  
  71. # Function to display text on the screen
  72. def display_text(text, color, x, y):
  73.     text_surface = font.render(text, True, color)
  74.     game_display.blit(text_surface, (x, y))
  75.  
  76. # Function to draw the snake
  77. def draw_snake(snake_list):
  78.     for i, segment in enumerate(snake_list):
  79.         color = BLACK if i == 0 else GREEN  # First block is black, rest are green
  80.         pygame.draw.rect(
  81.             game_display, color, [segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE]
  82.         )
  83.  
  84. # Function to display game over screen
  85. def game_over_screen(score):
  86.     game_display.fill(WHITE)
  87.     display_text(
  88.         "      Game Over !", RED, WINDOW_WIDTH / 2 - 100, WINDOW_HEIGHT / 2 - 30
  89.     )
  90.     display_text(
  91.         f"   Your Score: {score}", BLACK, WINDOW_WIDTH / 2 - 80, WINDOW_HEIGHT / 2 + 10
  92.     )
  93.     display_text(
  94.         "Press C to Play Again or Q to Quit",
  95.         BLACK,
  96.         WINDOW_WIDTH / 2 - 160,
  97.         WINDOW_HEIGHT / 2 + 50,
  98.     )
  99.     pygame.display.update()
  100.  
  101. # Function to fill background with gradient
  102. def draw_gradient_background():
  103.     for y in range(WINDOW_HEIGHT):
  104.         shade = int(
  105.             255 * (1 - (y / WINDOW_HEIGHT))
  106.         )  # Calculate shade based on y-coordinate
  107.         pygame.draw.rect(game_display, (0, shade, 0), (0, y, WINDOW_WIDTH, 1))
  108.  
  109. # Main game loop
  110. def game_loop():
  111.     snake_list = []
  112.     snake_length = 1
  113.     snake_head = [WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2]
  114.     direction = RIGHT
  115.     score = 0
  116.  
  117.     food_pos = [
  118.         random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE, BLOCK_SIZE),
  119.         random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE, BLOCK_SIZE),
  120.     ]
  121.  
  122.     game_exit = False
  123.     game_over = False
  124.  
  125.     while not game_exit:
  126.         while game_over:
  127.             game_over_screen(score)
  128.             for event in pygame.event.get():
  129.                 if event.type == pygame.QUIT:
  130.                     game_exit = True
  131.                     game_over = False
  132.                 if event.type == pygame.KEYDOWN:
  133.                     if event.key == pygame.K_q:
  134.                         game_exit = True
  135.                         game_over = False
  136.                     elif event.key == pygame.K_c:
  137.                         game_loop()
  138.  
  139.         for event in pygame.event.get():
  140.             if event.type == pygame.QUIT:
  141.                 game_exit = True
  142.             elif event.type == pygame.KEYDOWN:
  143.                 if event.key == pygame.K_LEFT and direction != RIGHT:
  144.                     direction = LEFT
  145.                 elif event.key == pygame.K_RIGHT and direction != LEFT:
  146.                     direction = RIGHT
  147.                 elif event.key == pygame.K_UP and direction != DOWN:
  148.                     direction = UP
  149.                 elif event.key == pygame.K_DOWN and direction != UP:
  150.                     direction = DOWN
  151.  
  152.         # Move the snake
  153.         if direction == UP:
  154.             snake_head[1] -= BLOCK_SIZE
  155.         elif direction == DOWN:
  156.             snake_head[1] += BLOCK_SIZE
  157.         elif direction == LEFT:
  158.             snake_head[0] -= BLOCK_SIZE
  159.         elif direction == RIGHT:
  160.             snake_head[0] += BLOCK_SIZE
  161.  
  162.         # Check for collision with food
  163.         if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
  164.             food_pos = [
  165.                 random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE, BLOCK_SIZE),
  166.                 random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE, BLOCK_SIZE),
  167.             ]
  168.             snake_length += 1
  169.             score += 10
  170.  
  171.         # Update the snake list
  172.         snake_list.insert(0, list(snake_head))
  173.         if len(snake_list) > snake_length:
  174.             del snake_list[-1]
  175.  
  176.         # Check for collision with walls or itself
  177.         if (
  178.             snake_head[0] >= WINDOW_WIDTH
  179.             or snake_head[0] < 0
  180.             or snake_head[1] >= WINDOW_HEIGHT
  181.             or snake_head[1] < 0
  182.             or snake_head in snake_list[1:]
  183.         ):
  184.             game_over = True
  185.  
  186.         # Fill the background with gradient
  187.         draw_gradient_background()
  188.  
  189.         # Draw the food
  190.         pygame.draw.rect(
  191.             game_display, RED, [food_pos[0], food_pos[1], BLOCK_SIZE, BLOCK_SIZE]
  192.         )
  193.  
  194.         # Draw the snake
  195.         draw_snake(snake_list)
  196.  
  197.         # Display score
  198.         display_text(f"Score: {score}", BLACK, 10, 10)
  199.  
  200.         # Update the display
  201.         pygame.display.update()
  202.  
  203.         # Set the FPS
  204.         clock.tick(FPS)
  205.  
  206.     pygame.quit()
  207.     quit()
  208.  
  209. # Start the game loop
  210. game_loop()
  211.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement