Skip to main content

Snake Game | Simple Snake Game written in Python using the PyGame Library.

Snake Game | Simple Snake Game written in Python using the PyGame Library. Vast Coding 


Here is the Source Code:-

"""

Snake Eater

Made with PyGame

"""


import pygame, sys, time, random



# Difficulty settings

# Easy      ->  10

# Medium    ->  25

# Hard      ->  40

# Harder    ->  60

# Impossible->  120

difficulty = 25


# Window size

frame_size_x = 720

frame_size_y = 480


# Checks for errors encountered

check_errors = pygame.init()

# pygame.init() example output -> (6, 0)

# second number in tuple gives number of errors

if check_errors[1] > 0:

    print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')

    sys.exit(-1)

else:

    print('[+] Game successfully initialised')



# Initialise game window

pygame.display.set_caption('Snake Eater')

game_window = pygame.display.set_mode((frame_size_x, frame_size_y))



# Colors (R, G, B)

black = pygame.Color(0, 0, 0)

white = pygame.Color(255, 255, 255)

red = pygame.Color(255, 0, 0)

green = pygame.Color(0, 255, 0)

blue = pygame.Color(0, 0, 255)



# FPS (frames per second) controller

fps_controller = pygame.time.Clock()



# Game variables

snake_pos = [100, 50]

snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]


food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]

food_spawn = True


direction = 'RIGHT'

change_to = direction


score = 0



# Game Over

def game_over():

    my_font = pygame.font.SysFont('times new roman', 90)

    game_over_surface = my_font.render('YOU DIED', True, red)

    game_over_rect = game_over_surface.get_rect()

    game_over_rect.midtop = (frame_size_x/2, frame_size_y/4)

    game_window.fill(black)

    game_window.blit(game_over_surface, game_over_rect)

    show_score(0, red, 'times', 20)

    pygame.display.flip()

    time.sleep(3)

    pygame.quit()

    sys.exit()



# Score

def show_score(choice, color, font, size):

    score_font = pygame.font.SysFont(font, size)

    score_surface = score_font.render('Score : ' + str(score), True, color)

    score_rect = score_surface.get_rect()

    if choice == 1:

        score_rect.midtop = (frame_size_x/10, 15)

    else:

        score_rect.midtop = (frame_size_x/2, frame_size_y/1.25)

    game_window.blit(score_surface, score_rect)

    # pygame.display.flip()



# Main logic

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            pygame.quit()

            sys.exit()

        # Whenever a key is pressed down

        elif event.type == pygame.KEYDOWN:

            # W -> Up; S -> Down; A -> Left; D -> Right

            if event.key == pygame.K_UP or event.key == ord('w'):

                change_to = 'UP'

            if event.key == pygame.K_DOWN or event.key == ord('s'):

                change_to = 'DOWN'

            if event.key == pygame.K_LEFT or event.key == ord('a'):

                change_to = 'LEFT'

            if event.key == pygame.K_RIGHT or event.key == ord('d'):

                change_to = 'RIGHT'

            # Esc -> Create event to quit the game

            if event.key == pygame.K_ESCAPE:

                pygame.event.post(pygame.event.Event(pygame.QUIT))


    # Making sure the snake cannot move in the opposite direction instantaneously

    if change_to == 'UP' and direction != 'DOWN':

        direction = 'UP'

    if change_to == 'DOWN' and direction != 'UP':

        direction = 'DOWN'

    if change_to == 'LEFT' and direction != 'RIGHT':

        direction = 'LEFT'

    if change_to == 'RIGHT' and direction != 'LEFT':

        direction = 'RIGHT'


    # Moving the snake

    if direction == 'UP':

        snake_pos[1] -= 10

    if direction == 'DOWN':

        snake_pos[1] += 10

    if direction == 'LEFT':

        snake_pos[0] -= 10

    if direction == 'RIGHT':

        snake_pos[0] += 10


    # Snake body growing mechanism

    snake_body.insert(0, list(snake_pos))

    if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:

        score += 1

        food_spawn = False

    else:

        snake_body.pop()


    # Spawning food on the screen

    if not food_spawn:

        food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]

    food_spawn = True


    # GFX

    game_window.fill(black)

    for pos in snake_body:

        # Snake body

        # .draw.rect(play_surface, color, xy-coordinate)

        # xy-coordinate -> .Rect(x, y, size_x, size_y)

        pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))


    # Snake food

    pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))


    # Game Over conditions

    # Getting out of bounds

    if snake_pos[0] < 0 or snake_pos[0] > frame_size_x-10:

        game_over()

    if snake_pos[1] < 0 or snake_pos[1] > frame_size_y-10:

        game_over()

    # Touching the snake body

    for block in snake_body[1:]:

        if snake_pos[0] == block[0] and snake_pos[1] == block[1]:

            game_over()


    show_score(1, white, 'consolas', 20)

    # Refresh game screen

    pygame.display.update()

    # Refresh rate

    fps_controller.tick(difficulty)


Output:-

Output

NOTE:- Please help me to grow my Youtube Channel called "Vast Coding"







Comments

Popular posts from this blog

Draw anyone's Sketch using Python Turtle Graphics in Python Programming

Draw anyone's Sketch using Python Turtle Graphics in Python Programming 👨‍💻🔥 In this post ,I will tell you about How to make Anyone's Sketch in Python using svg file and using these libraries: Turtle,cv2(opencv-python),svgpathtools,svg.path and tqdm. You can install these libraries using pip command. Turtle is pre-installed in mostly all programming softwares. And here are the pip commands to install other libraries : pip install opencv-python pip install svgpathtools pip install svg.path pip install tqdm 𝗦𝘁𝗲𝗽𝘀 𝘁𝗼 𝗺𝗮𝗸𝗲 𝘀𝗸𝗲𝘁𝗰𝗵 :  1)Go to https://svgconvert.com/#/  2)Upload the image and change the threshold value according to the image and download it as a svg file.  3)Save the code and svg file in the same folder.  Source Code : import turtle as tu import cv2 from svgpathtools import svg2paths2 from svg.path import parse_path from tqdm import tqdm class sketch_from_svg: def __init__(self,path,scale=30,x_offset=400,y_offset=400): self.path =

Robert Downey Jr - Tony Stark - Ironman Sketch using Python Turtle Graphics

Robert Downey Jr Sketch using Python Turtle Graphics 👨‍💻 About Python Turtle Graphics : Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967. Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle , give it the command turtle. Note: If you are facing any issue to copy the code then copy the full page clicking 'select all',paste it to your notepad and copy the code from there. Here is the source code : import turtle as tu class rdj: def __init__(self): self.mouth = [(374, 382),(368, 382),(359, 382),(347, 379),(339, 381),(334, 384),(323, 380),(315, 380),(293, 385),(321, 387),(339, 387),(345, 386),(357, 385),(374, 383),(-1, -1),(389, 389),(393, 387),(395, 381),(395, 373),(377, 362),(366, 357),(358, 360),(351, 357),(345, 354),(344, 357),(337, 355),(333, 357),(327, 355),(323, 357),(303, 362),(

Sketchpy Python Library | How to use and How to Install

How to use sketchpy library in python | How to install sketchpy library in python programming Hello visitors, In this blogpost I will tell you about new python library called ' Sketchpy ' It's a new library in python programming. You can consider sketchpy as beginning level python project. What is sketchpy? Sketchpy is a library which allows you to draw any sketch using turtle graphics. In sketchpy library there are several classes and you can import these classes and then draw Rdj,Thalapathy Vijay,Apj Abdul kalam ,etc. This library also contains very useful codes like image coordinates tracer ,etc Sketchpy is a beginning level python project to draw amazing and awesome animations,drawings,designs using python turtle graphics. Usage ⬤  Install the package using    pip install sketchpy ⬤  Import it as import sketchpy in your project How to Install ⬤   Install using Terminal ⬤    Install using CMD {Command Prompt} Install pip install sketchpy It will definetely work, bu