Snake game in Python with source code | Pygame in Python

  Step by Step Procedure to create Snake game in Python

Hello friends how are you, Today in this post "Snake game in Python" i am going to teach you how you can create your own Snake Game in Python using very simple lines of code. Snake game is on of the most popular game which every programmer or learner wants to create so here you will get the complete code for snake game.

If you are a computer science students or teacher and want to learn something interesting in programming then just go through this post. This can also be a simple and interesting project for you.

In Snake Game there are two main elements in which one is Snake and the other is Fruit. When snake eats fruit then its tail grows longer, making the increasingly difficult. Some important rules for snake game is below.

  1. Snake moves at constant speed
  2. Snake can move only in direction NORTH, SOUTH, EAST AND WEST
  3. Direction of snake can be controlled using UP, DOWN, LEFT AND RIGHT keys
  4. Fruit appears at random location.
  5. When snake eats Fruit its tail gets longer.
  6. When snake crosses itself the game will over.

If you want to understand this through video then watch this video i have explained it step by step live

Now  i am going to explain it step by step so just go through this post to understand this completely.

Step 1: Install Python : Click here to watch a video on how to install python or Open any browser and type Download Python and click the first link you will get official website of python here you will get a Download button and after clicking on this button you will get exe of latest python version just install it into your system. 

Step 2: Install Pycharm | Create Project | Install LibraryClick here to watch a single video on How to install Pycharm | Create Project | Install Library  or To install Pycharm IDE Open any browser and type Download Pycharm and click the first link you will get official website of Pycharm  here you will get a black download button and after clicking on this button you will get an exe of Pycharm , just install it into your system. If you are facing problem to install then watch the above video i have explained step by step.

Step 3: Create Project : Open Pycharm  click on File which is in top left of screen and select New Project. Then you will get a screen. Here first you need to select directory of your project and then type a name for your project like "SnakeGame" after directory name, and at last click the create button to create this project. 

Step 4: Create Python file: To create a python file for coding in your project just right click on project name "SnakeGame" and select new and click on Python File , you will get popup screen in which you have to type a name like "Program" for python file and press enter, it will create a python file with name Program.py inside the project SnakeGame. 

If you want to learn complete Python for Free the click here 

Step 5:Python code:  Here is the complete code for this project/program you just need to type this code into your python file or you can copy this code for your personal use.

"""
krazyprogrammers Presents Snake Game in Python
"""
#import library
from pygame.locals import *
from random import randint
import pygame
import time

#defining class for fruit
class Fruit:
    x = 0
    y = 0
    step = 44

    def __init__(self, x, y):
        self.x = x * self.step
        self.y = y * self.step

    def draw(self, surface, image):
        surface.blit(image, (self.x, self.y))

#defining class for player
class Player:
    x = [0]
    y = [0]
    step = 44
    direction = 0
    length = 3

    updateCountMax = 2
    updateCount = 0
    #constructor
    def __init__(self, length):
        self.length = length
        for i in range(0, 2000):
            self.x.append(-100)
            self.y.append(-100)

        # initial positions, no collision.
        self.x[1] = 1 * 44
        self.x[2] = 2 * 44

    def update(self):

        self.updateCount = self.updateCount + 1
        if self.updateCount > self.updateCountMax:

            # update previous positions
            for i in range(self.length - 1, 0, -1):
                self.x[i] = self.x[i - 1]
                self.y[i] = self.y[i - 1]

            # update position of head of snake
            if self.direction == 0:
                self.x[0] = self.x[0] + self.step
            if self.direction == 1:
                self.x[0] = self.x[0] - self.step
            if self.direction == 2:
                self.y[0] = self.y[0] - self.step
            if self.direction == 3:
                self.y[0] = self.y[0] + self.step

            self.updateCount = 0

    def moveRight(self):
        self.direction = 0

    def moveLeft(self):
        self.direction = 1

    def moveUp(self):
        self.direction = 2

    def moveDown(self):
        self.direction = 3

    def draw(self, surface, image):
        for i in range(0, self.length):
            surface.blit(image, (self.x[i], self.y[i]))

#defining class for game
class Game:
    def isCollision(self, x1, y1, x2, y2, bsize):
        if x1 >= x2 and x1 <= x2 + bsize:
            if y1 >= y2 and y1 <= y2 + bsize:
                return True
        return False


class Application:
    winWidth = 700
    winHeight = 700
    player = 0
    fruit = 0

    def __init__(self):
        self._running = True
        self.displaySurface = None
        self.imgSurface = None
        self.fruitSurface = None
        self.game = Game()
        self.player = Player(1)
        self.fruit = Fruit(5, 5)

    def on_init(self):
        pygame.init()
        self.displaySurface = pygame.display.set_mode((self.winWidth, self.winHeight), pygame.HWSURFACE)

        pygame.display.set_caption('krazyprogrammers')
        self._running = True
        #set an image  of size 30x30 for snake
        self.imgSurface = pygame.image.load("snake.png").convert()
        # set an image  of size 30x30 for fruit
        self.fruitSurface = pygame.image.load("fruit.png").convert()

    def on_event(self, event):
        if event.type == QUIT:
            self._running = False

    def on_loop(self):
        self.player.update()

        # does snake eat fruit?
        for i in range(0, self.player.length):
            if self.game.isCollision(self.fruit.x, self.fruit.y, self.player.x[i], self.player.y[i], 44):
                self.fruit.x = randint(2, 9) * 44
                self.fruit.y = randint(2, 9) * 44
                self.player.length = self.player.length + 1

        # does snake collide with itself?
        for i in range(2, self.player.length):
            if self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], 40):
                print("Snake Collision: ")
                exit(0)

        pass

    def on_render(self):
        #set background color
        self.displaySurface.fill((0,0,0))
        self.player.draw(self.displaySurface, self.imgSurface)
        self.fruit.draw(self.displaySurface, self.fruitSurface)
        pygame.display.flip()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        while (self._running):
            pygame.event.pump()
            keys = pygame.key.get_pressed()

            if (keys[K_RIGHT]):
                self.player.moveRight()

            if (keys[K_LEFT]):
                self.player.moveLeft()

            if (keys[K_UP]):
                self.player.moveUp()

            if (keys[K_DOWN]):
                self.player.moveDown()
            #press esc button to terminate the application
            if (keys[K_ESCAPE]):
                self._running = False
            self.on_loop()
            self.on_render()
            time.sleep(50.0 / 1000.0);
        self.on_cleanup()

#running application
if __name__ == "__main__":
    objApp = Application()
    objApp.on_execute()

Just copy this code from here and paste it into program.py .


Step 8: Run Code: To run this code just right click on the coding area and click on Run Program and you will get a output screen like below.



I hope now you can  create "Snake game in Python ". If you have any doubt regarding this post  or you want something more in this post then let me know by comment below i will work on it definitely.
 

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

If you like my post then share it with your friends. Thanks😊Happy Coding.

Post a Comment

2 Comments

  1. Looking at your snake game in python, where would I find the two .pnl files - fruit and apple?

    ReplyDelete