Here’s a simple Snake game implemented in Python using the pygame library. You can run this code to play a classic version of the game.

This script creates a simple Snake game where:

  • Use arrow keys to move the snake.
  • The snake grows in length as it eats the red square (food).
  • The game ends if the snake collides with itself or the boundary.

To run this code:

  1. Ensure Python and the pygame library are installed.
    • Install pygame via pip: pip install pygame
  2. Save the code in a .py file and execute it.

Enjoy the game! 🎮

Source code –

import pygame

import time

import random

# Initialize pygame

pygame.init()

# Screen dimensions

WIDTH, HEIGHT = 800, 600

# Colors

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLUE = (0, 0, 255)

# Snake settings

SNAKE_BLOCK = 20

SNAKE_SPEED = 15

# Initialize screen

dis = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption(‘Snake Game’)

# Clock for controlling speed

clock = pygame.time.Clock()

# Font settings

font_style = pygame.font.SysFont(None, 50)

score_font = pygame.font.SysFont(None, 35)

def our_snake(snake_block, snake_list):

    for x in snake_list:

        pygame.draw.rect(dis, GREEN, [x[0], x[1], snake_block, snake_block])

def message(msg, color, x, y):

    msg_surface = font_style.render(msg, True, color)

    dis.blit(msg_surface, [x, y])

def your_score(score):

    value = score_font.render(f”Your Score: {score}”, True, BLUE)

    dis.blit(value, [10, 10])

def game_loop():

    game_over = False

    game_close = False

    # Initial position of the snake

    x1 = WIDTH // 2

    y1 = HEIGHT // 2

    # Movement direction

    x1_change = 0

    y1_change = 0

    # Snake body

    snake_list = []

    length_of_snake = 1

    # Food position

    food_x = round(random.randrange(0, WIDTH – SNAKE_BLOCK) / 20.0) * 20.0

    food_y = round(random.randrange(0, HEIGHT – SNAKE_BLOCK) / 20.0) * 20.0

    while not game_over:

        while game_close:

            dis.fill(BLACK)

            message(“You Lost! Press Q-Quit or C-Play Again”, RED, WIDTH // 10, HEIGHT // 3)

            your_score(length_of_snake – 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 and x1_change == 0:

                    x1_change = -SNAKE_BLOCK

                    y1_change = 0

                elif event.key == pygame.K_RIGHT and x1_change == 0:

                    x1_change = SNAKE_BLOCK

                    y1_change = 0

                elif event.key == pygame.K_UP and y1_change == 0:

                    x1_change = 0

                    y1_change = -SNAKE_BLOCK

                elif event.key == pygame.K_DOWN and y1_change == 0:

                    x1_change = 0

                    y1_change = SNAKE_BLOCK

        # Check boundaries

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

            game_close = True

        x1 += x1_change

        y1 += y1_change

        dis.fill(BLACK)

        pygame.draw.rect(dis, RED, [food_x, food_y, SNAKE_BLOCK, SNAKE_BLOCK])

        snake_head = []

        snake_head.append(x1)

        snake_head.append(y1)

        snake_list.append(snake_head)

        if len(snake_list) > length_of_snake:

            del snake_list[0]

        for block in snake_list[:-1]:

            if block == snake_head:

                game_close = True

        our_snake(SNAKE_BLOCK, snake_list)

        your_score(length_of_snake – 1)

        pygame.display.update()

        if x1 == food_x and y1 == food_y:

            food_x = round(random.randrange(0, WIDTH – SNAKE_BLOCK) / 20.0) * 20.0

            food_y = round(random.randrange(0, HEIGHT – SNAKE_BLOCK) / 20.0) * 20.0

            length_of_snake += 1

        clock.tick(SNAKE_SPEED)

    pygame.quit()

    quit()

# Start the game

game_loop()

Share with our team

Leave a Comment