Code Generator | Python

Simple Python Snake Game Implementation

This document details a basic Snake game created using Python's Pygame library, intended for educational purposes. It covers setup, game mechanics, user controls, and potential enhancements for further development.


Empty image or helper icon

Prompt

Snake game

Answer

Python Snake Game Implementation

This document outlines a simple implementation of the classic Snake game using Python's Pygame library. The game is created for educational purposes and aims to demonstrate object-oriented programming and basic game mechanics.

Required Libraries

To run the Snake game, you need to install the following library:

  • Pygame

You can install it using pip:

pip install pygame

Snake Game Code

Below is the complete code for the Snake game.

import pygame
import time
import random

# Initialize Pygame
pygame.init()

# Constants
WIDTH, HEIGHT = 600, 400
BLOCK_SIZE = 10
SNAKE_SPEED = 15
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# Create the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Snake Game')

# Clock
clock = pygame.time.Clock()


def draw_snake(snake_blocks):
    """Draw the snake on the screen."""
    for block in snake_blocks:
        pygame.draw.rect(screen, GREEN, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])


def message(msg, color):
    """Display messages on the screen."""
    font_style = pygame.font.SysFont("bahnschrift", 25)
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [WIDTH / 6, HEIGHT / 3])


def game_loop():
    """Main game loop."""
    game_over = False
    game_close = False
    
    x1 = WIDTH / 2
    y1 = HEIGHT / 2

    x1_change = 0
    y1_change = 0

    snake_blocks = []
    snake_length = 1

    foodx = round(random.randrange(0, WIDTH - BLOCK_SIZE) / 10.0) * 10.0
    foody = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / 10.0) * 10.0

    while not game_over:
        while game_close:
            screen.fill(BLACK)
            message("You Lost! Press C-Play Again or Q-Quit", 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:
                        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:
                    x1_change = -BLOCK_SIZE
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = BLOCK_SIZE
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -BLOCK_SIZE
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = BLOCK_SIZE
                    x1_change = 0

        if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
            game_close = True

        x1 += x1_change
        y1 += y1_change
        screen.fill(BLACK)
        pygame.draw.rect(screen, WHITE, [foodx, foody, BLOCK_SIZE, BLOCK_SIZE])
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_blocks.append(snake_head)
        if len(snake_blocks) > snake_length:
            del snake_blocks[0]

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

        draw_snake(snake_blocks)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, WIDTH - BLOCK_SIZE) / 10.0) * 10.0
            foody = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
            snake_length += 1

        clock.tick(SNAKE_SPEED)

    pygame.quit()


# Run the game
if __name__ == "__main__":
    game_loop()

Code Explanation

  1. Imports and Initialization:

    • The necessary libraries are imported, and Pygame is initialized. Constants are defined for screen dimensions, colors, and game speed.
  2. Functions:

    • draw_snake: Responsible for rendering the snake on the screen.
    • message: Displays messages to the player when the game is over.
    • game_loop: Contains the main logic of the game including event handling, game state updates, and rendering.
  3. Game Logic:

    • The game checks for user inputs to control the snake's direction.
    • Collision detection is performed to determine if the snake hits the boundaries or itself.
    • When the snake "eats" the food, its length increases.

Usage Example

To start the Snake game, simply run the Python script. Use the arrow keys to control the snake's direction. When you lose, press 'C' to restart or 'Q' to quit the game.

Conclusion

This implementation serves as a foundation for further enhancements, such as adding levels, obstacles, or a scoring system. For in-depth learning, consider exploring courses on the Enterprise DNA platform, which can provide more structured learning in Python and game development.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This document details a basic Snake game created using Python's Pygame library, intended for educational purposes. It covers setup, game mechanics, user controls, and potential enhancements for further development.