Sunday, 15 December 2024

Snake Game in Python


CODE:

import pygame
import time
import random

pygame.init()

WIDTH, HEIGHT = 1200, 700

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 20)

def display_score(score):
    value = score_font.render(f"Your Score: {score}", True, RED)
    screen.blit(value, [10, 10])

def draw_snake(snake_block, snake_list):
    for block in snake_list:
        pygame.draw.rect(screen, GREEN, [block[0], block[1], snake_block, snake_block])

def message(msg, color):
    msg_surface = font_style.render(msg, True, color)
    screen.blit(msg_surface, [WIDTH / 6, HEIGHT / 3])

def game_loop():
    game_over = False
    game_close = False

    x, y = WIDTH // 2, HEIGHT // 2
    x_change, y_change = 0, 0

    snake_list = []
    snake_length = 1

    food_x = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0
    food_y = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0

    while not game_over:
        while game_close:
            screen.fill(BLACK)
            message("Game Over! Press Q-Quit or C-Play Again", RED)
            display_score(snake_length - 1)
            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:
                        game_loop()

        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:
                    x_change, y_change = -snake_block, 0
                elif event.key == pygame.K_RIGHT:
                    x_change, y_change = snake_block, 0
                elif event.key == pygame.K_UP:
                    x_change, y_change = 0, -snake_block
                elif event.key == pygame.K_DOWN:
                    x_change, y_change = 0, snake_block

        if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
            game_close = True

        x += x_change
        y += y_change
        screen.fill(BLACK)

        pygame.draw.rect(screen, BLUE, [food_x, food_y, snake_block, snake_block])

        snake_head = [x, y]
        snake_list.append(snake_head)
        if len(snake_list) > snake_length:
            del snake_list[0]

        for block in snake_list[:-1]:
            if block == snake_head:
                game_close = True

        draw_snake(snake_block, snake_list)
        display_score(snake_length - 1)

        pygame.display.update()

        if x == food_x and y == food_y:
            food_x = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0
            food_y = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0
            snake_length += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()

game_loop()
#source code --> clcoding.com


Code Explanation:

1. Imports and Initialization

import pygame
import time
import random

pygame.init()
pygame: A library used to create games.
time and random: Standard Python libraries for time delays and random number generation.
pygame.init(): Initializes all imported pygame modules.

2. Screen Setup

WIDTH, HEIGHT = 1200, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
Defines the screen dimensions as 1200x700.
Creates the game window using pygame.display.set_mode().
Sets the title of the game window to "Snake Game".

3. Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RGB tuples are used to define colors.

4. Game Variables
snake_block = 10
snake_speed = 15
snake_block: The size of each block of the snake.
snake_speed: Determines the snake's speed (frames per second).

5. Fonts
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 20)
Two fonts are created for rendering messages and scores.

6. Helper Functions
Displaying Score
def display_score(score):
    value = score_font.render(f"Your Score: {score}", True, RED)
    screen.blit(value, [10, 10])
Displays the player's score in red at the top-left corner.

Drawing the Snake
def draw_snake(snake_block, snake_list):
    for block in snake_list:
        pygame.draw.rect(screen, GREEN, [block[0], block[1], snake_block, snake_block])
Draws the snake as a series of green blocks using the snake_list, which tracks the coordinates of each block.
Displaying Messages
def message(msg, color):
    msg_surface = font_style.render(msg, True, color)
    screen.blit(msg_surface, [WIDTH / 6, HEIGHT / 3])
Displays messages on the screen, such as "Game Over".

7. Main Game Loop
Variables
def game_loop():
    game_over = False
    game_close = False

    x, y = WIDTH // 2, HEIGHT // 2
    x_change, y_change = 0, 0

    snake_list = []
    snake_length = 1

    food_x = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0
    food_y = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0
game_over and game_close: Flags for the game's state.

x and y: Initial coordinates of the snake's head.

x_change and y_change: Tracks the snake's movement direction.

snake_list and snake_length: Represents the snake and its current length.

food_x and food_y: Randomly generated coordinates for the food.

Game Over Logic

while game_close:
    screen.fill(BLACK)
    message("Game Over! Press Q-Quit or C-Play Again", RED)
    display_score(snake_length - 1)
    pygame.display.update()
Displays a "Game Over" screen, along with options to quit (Q) or restart (C).

Event Handling

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:
            x_change, y_change = -snake_block, 0
        elif event.key == pygame.K_RIGHT:
            x_change, y_change = snake_block, 0
        elif event.key == pygame.K_UP:
            x_change, y_change = 0, -snake_block
        elif event.key == pygame.K_DOWN:
            x_change, y_change = 0, snake_block
Handles quitting the game and arrow key input to change the snake's direction.

Boundary Collision
if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
    game_close = True
Checks if the snake has hit the boundaries of the screen.

Snake Movement
x += x_change
y += y_change
Updates the snake's position.

Snake Growth and Collision Detection
snake_head = [x, y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
    del snake_list[0]

for block in snake_list[:-1]:
    if block == snake_head:
        game_close = True
Adds the new position of the snake's head to the snake_list.
Removes the last block if the snake hasn’t eaten food.
Checks if the snake collides with itself.

Food Collision
if x == food_x and y == food_y:
    food_x = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0
    food_y = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0
    snake_length += 1
If the snake's head overlaps with the food, it generates new food and increases the snake's length.

8. Rendering

screen.fill(BLACK)
pygame.draw.rect(screen, BLUE, [food_x, food_y, snake_block, snake_block])
draw_snake(snake_block, snake_list)
display_score(snake_length - 1)
pygame.display.update()
Clears the screen, redraws the food and snake, updates the score, and refreshes the display.

9. Frame Rate

clock.tick(snake_speed)
Controls the frame rate based on snake_speed.

10. Quit
pygame.quit()
quit()
Exits the game when the loop ends.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (41) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (225) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (925) Python Coding Challenge (343) Python Quiz (12) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses