Snake Game Python Code: How to Build an Addictive Game in Just a Few Lines

The Snake Game Python code is a typical first programming project. Learning about object-oriented programming, graphical user interfaces, and game design is a great way. The game can be built with the help of many libraries, such as Py game, Turtle, and Tinter.

In the old game Python Snake, you play as a snake, and your goal is to eat food and get longer as you gain control. The code for the game was written in the programming language Python, and it is played with a graphical user interface (GUI).

The player’s job is to direct the Snake with the arrow keys or WASD to eat the random bits of food that appear on the screen. The Snake gets longer as it consumes the food, and the player’s score increases. But if the Snake hits a wall or its own body, the game is over.

In this article, we have covered the following Python code topics:

  • Python Game Code in Simple Form
  • Snake Game Project Report in Python
  • Snake Game Python Code 
  • Python Snake Game Code without Pygame

Python Game Code in Simple Form

In Python, a simple guessing game is as follows:

import random

secret_number = random.randint(1, 10)

attempts = 0

while attempting 3:

    guess = int(input(“Guess the secret number (between 1 and 10): “))

    attempts += 1

    If guess == secret_number:

        print(“Congratulations! You guessed the secret number!”)

        break

    elif guess < secret_number:

        print(“The secret number is higher than your guess.”)

    else:

        print(“The secret number is lower than your guess.”)

else:

    print (“Sorry, you have run out of attempts. The secret number was”, secret_number)

This code loads the random module and calls its random.randint() function to get a random number between 1 and 10. The system asks the user to guess how many there are and gives them three chances. If the user’s guess was correct, the software shows a message of congratulations and ends the loop with the keyword “break.” When the user has tried everything, the programme offers a statement with the answer.

Snake Game Project Report in Python

Introduction:

The first Snake Game arcade cabinet was made in the 1970s. The player must move a snake across the screen as it eats and gets bigger. The game ends when the Snake hits a wall or its tail. This assignment aims to use the Python programming language to make a game like the classic Snake.

A Look at the Project:

Since Python’s Pygame module is used to make games and other multimedia programmes, it will be the primary tool for making the Snake Game. In this action platformer, the player is in charge of a snake that must eat food while avoiding walls and even it’s tail. The Snake will grow longer as it consumes more food, but the game will end if it runs into anything, even itself.

More technical information:

The game will be made up of the following technical components:

This library, called Pygame, is a group of Python modules and functions that can be used to make games and other multimedia programmes. Pygame will be used to make the game’s window, controls, visuals, and sounds.

The main loop always going on in a game is called the “game loop.” It handles what the user types, saves the game’s progress, and draws the UI.

The hero of the game is a snake. The player tells it what to do as it eats and moves around the screen, getting more significant. The Snake is made up of a series of rectangles, each of which represents a different part of the Snake’s body.

The Snake must try to eat the food on the screen randomly. The Snake eats the food and gets longer because of it.

It’s important to know immediately when the Snake hits a wall or its tail so that the problem can be fixed. The game is over as soon as a collision is found.

The game keeps track of the player’s score, which goes up every time the Snake eats an item.

Sound effects are essential to gaming because they give you feedback and help you get into the game. The Snake will make different sounds when it eats, bumps into things, or runs into its tail.

Conclusion:

People worldwide have played the Snake Game for decades because it is fun and challenging. It’s a great way to learn Python and make games while learning. By making this game, you’ll learn how to use the Pygame library, handle user input, create graphics, and assemble game logic. If you take the time to think outside the box, you can make the game even more fun and exciting.

Snake Game Python Code

Snake Game Python Code

Here is the Python script for a simple Snake Game made with Pygame. Just create a new Python file and use the following code to play the game.

import pygame

import random

# initialize Pygame

pygame.init()

# define colors

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

GREEN = (0, 255, 0)

RED = (255, 0, 0)

# set screen dimensions

SCREEN_WIDTH = 500

SCREEN_HEIGHT = 500

# set the size of each segment of the Snake

SEGMENT_SIZE = 20

# create the game window

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# set the title of the game window

pygame.display.set_caption(“Snake Game”)

clock = pygame.time.Clock()

# define the Snake class

class Snake:

    def __init__(self):

        self.segments = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]

        self.direction = random.choice([“up”, “down”, “left”, “right”])

    def move(self):

        x, y = self.segments[0]

        if self.direction == “up”:

            y -= SEGMENT_SIZE

        elif self.direction == “down”:

            y += SEGMENT_SIZE

        elif self.direction == “left”:

            x -= SEGMENT_SIZE

        elif self.direction == “right”:

            x += SEGMENT_SIZE

        self.segments.insert(0, (x, y))

        self.segments.pop()

    def draw(self):

        for segment in self.segments:

            pygame.draw.rect(screen, GREEN, (segment[0], segment[1], SEGMENT_SIZE, SEGMENT_SIZE))

    def change_direction(self, direction):

        if direction == “up” and self.direction != “down”:

            self.direction = “up”

        elif direction == “down” and self.direction != “up”:

            self.direction = “down”

        elif direction == “left” and self.direction != “right”:

            self.direction = “left”

        elif direction == “right” and self.direction != “left”:

            self.direction = “right”

    def grow(self):

        x, y = self.segments[-1]

        if self.direction == “up”:

            y += SEGMENT_SIZE

        elif self.direction == “down”:

            y -= SEGMENT_SIZE

        elif self.direction == “left”:

            x += SEGMENT_SIZE

        elif self.direction == “right”:

            x -= SEGMENT_SIZE

        self.segments.append((x, y))

    def check_collision(self):

        x, y = self.segments[0]

        if x < 0 or x > SCREEN_WIDTH – SEGMENT_SIZE or y < 0 or y > SCREEN_HEIGHT – SEGMENT_SIZE:

            return True

        for segment in self.segments[1:]:

            if x == segment[0] and y == segment[1]:

                return True

        return False

# define the Food class

class Food:

    def __init__(self):

        self.position = (0, 0)

        self.generate_position()

    def draw(self):

        pygame.draw.rect(screen, RED, (self.position[0], self.position[1], SEGMENT_SIZE, SEGMENT_SIZE))

    def generate_position(self):

        x = random.randint(0, SCREEN_WIDTH – SEGMENT_SIZE)

        y = random.randint(0, SCREEN_HEIGHT – SEGMENT_SIZE)

        self.position = (x, y)

# create the Snake and Food objects

snake = Snake()

food = Food()

# set the initial score to 0

score = 0

# define the game loop

while True:

    # handle events

You Must Watch: A Perspective on Spring Boot Interview Questions

Python Snake Game Code without Pygame

Here’s a simple way to make a Snake game using only Python’s basic features without pygame

import curses

from random import randint

# Initialize the game window

window = curses.initscr()

curses.curs_set(0) # Hide cursor

window_height, window_width = window.getmaxyx()

# Initialize the Snake

snake_x = window_width//2

snake_y = window_height//2

snake = [[snake_y, snake_x-1], [snake_y, snake_x], [snake_y, snake_x+1]]

snake_direction = curses.KEY_RIGHT

# Initialize the food

food = [randint(1, window_height-2), randint(1, window_width-2)]

# Display the food

window.addch(food[0], food[1], ‘O’)

# Main game loop

while True:

    # Move the Snake

    new_head = [snake[0][0], snake[0][1]]

    if snake_direction == curses.KEY_RIGHT:

        new_head[1] += 1

    elif snake_direction == curses.KEY_LEFT:

        new_head[1] -= 1

    elif snake_direction == curses.KEY_UP:

        new_head[0] -= 1

    elif snake_direction == curses.KEY_DOWN:

        new_head[0] += 1

    snake.insert(0, new_head)

    # Check if the Snake collided with the border or itself

    if (snake[0][0] == 0 or snake[0][0] == window_height-1 or

        snake[0][1] == 0 or snake[0][1] == window_width-1 or

        snake[0] in snake[1:]):

        curses.endwin()

        quit()

    # Check if the snake ate the food

    if snake[0] == food:

        food = [randint(1, window_height-2), randint(1, window_width-2)]

        window.addch(food[0], food[1], ‘O’)

    else:

        tail = Snake.pop()

        window.addch(tail[0], tail[1], ‘ ‘)

    # Display the Snake

    for i, point in enumerate(Snake):

        if i == 0:

            window.addch(point[0], point[1], curses.ACS_CKBOARD)

        else:

            window.addch(point[0], point[1], curses.ACS_BLOCK)

    # Get user input

    key = window.getch()

    if key in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_UP, curses.KEY_DOWN]:

        snake_direction = key

    elif key == 27: # ESC key

        curses.endwin()

        quit()

In this implementation, the curses module makes a text-based user interface for the game. The block symbol represents the Snake █, the letter O represents the food, and the ASCII character # represents the border. The player directs the Snake with the arrow keys, and the game ends when it touches the edge of the screen or itself. To quit the game, press the ESC key.

Conclusion

The Python Snake game is a great place to start if you want to learn how to code and make games. This fun and challenging game can be made with libraries like Pygame, Turtle, or Tkinter. It will test your reflexes and your ability to think strategically.

The Python Snake game is made by creating the rules, designing the user interface, and coding them, so they work. The code for the game may seem difficult at first, but it can be broken up into smaller pieces that can be performed one at a time.

Object-oriented programming ideas like classes and inheritance can be used in the Python Snake game. This makes it an excellent choice for people just starting with programming. Beginners can learn about OOP by using classes to make the snake, food objects, and inheritance to make different kinds of food.

In conclusion, the Python Snake game can be changed and improved in many ways. These include adding sound effects, new levels, and even new power-ups. So, it is an excellent way for beginners to improve their skills while making a fun and enjoyable game.

Press ESC to close