Code a Snake Game with Python and Pygame 🐍 – Tutorial

Wordpress sites

In this Python / Pygame tutorial you will build a snake and apple game. This Python project for beginners is perfect for you to get exposure on how you can build an end-to-end Python project after learning the basics of Python.

✏️ Course created by Dhaval Patel from codebasics. Check out his channel:

💻 Code:

🎥 Watch the Hindi version of this course:

⭐️ Course Contents ⭐️
⌨️ (0:00:00) Intro and create surface
⌨️ (0:21:03) Converting into OOP
⌨️ (0:31:48) Moving block with timer
⌨️ (0:37:10) Draw snake and apple
⌨️ (0:49:34) Snake eats apple, find score
⌨️ (1:07:33) Game over logic
⌨️ (1:20:07) Add background music,image
⌨️ (1:31:45) Convert python to exe

🎉 Thanks to our Champion supporters:
Otis Morgan
DeezMaster
Katia Moran

Learn to code for free and get a developer job:

Read hundreds of articles on programming:

And subscribe for new videos on technology every day:

39 thoughts on “Code a Snake Game with Python and Pygame 🐍 – Tutorial”

    1. Hey codebasics! just finished the tutorial, learned a lot about OOP and pygame! I also liked how you made it so that the finished product is basically a bare-bones snake game, and there is a lot you can do to personalize and improve on it. I’m gonna work on this game for the next few days. Thanks again!

    1. Aditya Agarwal

      at 47:43 its showing — ‘Apple’ object has no attribute ‘image’. Plzzz helpp!!!!!

  1. Your coordinate system for the y1 and y2 must be reversed – The y axis increments while the snake is going down this is the part why I confused haha by the way I understood it. Thanks!

    1. The window is drawn from the top pixel down, which is why it’s flipped. Throws everyone i have seen off lol!

    1. Aditya Agarwal

      at 47:43 its showing — ‘Apple’ object has no attribute ‘image’. Plzzz helpp!!!!!

  2. FYI, when you start the 3rd section (Moving block with timer), he changes the Snake __init__ to (self, surface). I was trying to debug why mine wasn’t running haha

  3. Satyajit Patra

    Thank you so much for helping to understand the project. This is an wonderful project for python beginner.
    But sir I have little problem with your code. ” When the snake is going to one direction, it can’t go to it’s reverse direction directly. First of all the snake has to take either left or right turn then the snake has to take another left or right turn. Then only the snake can go to it’s reverse direction according to it’s first direction”.

    1. Satyajit Patra

      For more specific, suppose “the Snake’s direction is upwards. Now Snake can’t go to downwards direction directly. First the Snake has to turn to it’s left or right and then the Snake has to take another left or right turn simultaneously to go to downwards direction”.
      But Sir, in your section Snake can change its reverse direction directly.

    2. Satyajit Patra

      I think, I debug the problem. This little problem can easily solve by little bit update.
      def move_up(self):
      if not(self.direction == “down”):
      self.direction = “up”

      def move_down(self):
      if not (self.direction == “up”):
      self.direction = “down”

      def move_right(self):
      if not (self.direction == “left”):
      self.direction = “right”

      def move_left(self):
      if not (self.direction == “right”):
      self.direction = “left”

    3. @Satyajit Patra thanks for that! I also added this, so that when youre at score = 1 you can move backwards, as you wouldnt be crashing into yourself:

      def move_left(self):
      if self.length == 1:
      self.direction = ‘left’
      if not(self.direction == “right”):
      self.direction = ‘left’

      def move_right(self):
      if self.length == 1:
      self.direction = ‘right’
      if not(self.direction == “left”):
      self.direction = ‘right’

      def move_down(self):
      if self.length == 1:
      self.direction = ‘down’
      if not(self.direction == “up”):
      self.direction = ‘down’

      def move_up(self):
      if self.length == 1:
      self.direction = ‘up’
      if not(self.direction == “down”):
      self.direction = ‘up’

  4. Hi, I am not able to change the pause speed at the end of the tutorial. I wanted it to be a bit faster so I reduced the time constant but it still looks the same.

  5. For me the best way to learn something is not discuss about abstract concepts but doing like this ‘LIVE CODING’ because it shows us how to do it and contributes to acquiring all the concepts by examples.
    Tks again freecodecamp 🇧🇷🇧🇷🇧🇷

  6. Clément Gathellier

    If you’re on Linux and having trouble with the sounds triggering the “game over”, try converting them to ogg.

    Plus, in the play() method the error is not raised correctly, try replacing it by : raise ValueError(“Game over”)
    Then in the try except block (in the run() method) : except ValueError: instead of except Exception as e:

    This way the game will “game over” only when intended, not every time there’s a error occuring in the play() method

    Thanks for this tutorial, i’ve learned a LOT 🙂

  7. Joshua Schweizer

    is there a way, to block a crash if pressing the key for the opposite direction? basically that the snake just moves to the right and when i press the key to the left, it just ignores the input? Thanks in advance for every help!

  8. To complete this excelent tutorial, I want to leave my contribution for make limits in our display, if snake touch this limits then game will be over

    In class Game, make a new def named “limit” —- def limit(self, x1, x2, y1, y2):
    then define a condition : if x1 >= x2 or x1 < 0 or y1 >= y2 or y1 <0:
    return True

    after, into "def play (self):
    call the def limit under snake colliding with apple condition

    if self.limit(self.snake.x[0], x_w, self.snake.y[0], y_h):
    raise "Game Over"

  9. Andrey Zhigachev

    Thank you for preparing a great tutorial on OOP approach to game creation in Python! I totally enjoyed it and learned a lot from it.

  10. Rafy-Ivan Morales

    Rafy-Ivan Morales
    0 seconds ago
    I’m a new student trying to learn, so I can become a programmer with python and I have a project on how to make a port scan.

    So far I already make a port scan with Python3, and it scans fine, give a date and everything working good so far.

    I see on your video tutorial, it is very good.

    I would like to ask for your advice if you can and guide me on how I will add this 3
    in a Python script, I have:

    2. System should look for all the ports between the range of 1 to 1025
    3. If the Ports is open, it should create a file and add an entry for port number
    4. In case of any exception for instance “host is not available”, “host name could not be resolved” or
    due to any other error, you need to write that exception into the same file.

    Thank you and Merry Christmas.

  11. Nice tutorial, thank you very much:) I have a problem with the step where I add sounds. I did everything exactly as in the tutorial, but my game just exits whenever the snake eats the apple. If I delete the lines with pygame.mixer everything works normally. Anybody knows what might cause the issue?

    1. Does the terminal show any errors? Typically the file path or the name of the file is wrong it’ll say ‘FileNotFoundError’

    2. @Alex Wilkins It shows: pygame.error: Failed loading libmpg123-0.dll I tried downloading this library and putting it in System32. Didnt work.

  12. slug in a tub

    with the collision, since everything is on a grid, you can just make it:

    if y1 == y2:
    ifx1 == x2:
    (collision stuff)

Comments are closed.