🐍 Create Snake Game with Python PyGame: Intro to Game Development! 🐍
Unlock 1 Month of FREE Premium Access to Our Best Courses! 🎓✨ Sign up today and elevate your skills: https://techblazes.com 🚀 (ONLY GOOD FOR THE FIRST 10 PEOPLE TO PARTICIPATE)
Ever wanted to create your own game? This tutorial will guide you through building the classic Snake Game using Python and PyGame! Perfect for beginners, this video introduces you to the basics of game development while teaching you how to code a fun and interactive game.
✅ What You’ll Learn:
How to set up and use PyGame for game development.
Step-by-step instructions to create the Snake Game from scratch.
Tips for adding features like scoring and game-over logic.
By the end of this tutorial, you'll have a fully functional Snake Game and the skills to start creating your own games. Dive into game development with Python today!
🔔 Subscribe for more Python tutorials, game development tips, and coding projects!
This course teaches you how to make the 2d game snake with Python. You will learn to use the module pygame. pygame is a Python game development library designed for use with the The Python programming language. pygame is designed to provide low level access to audio, keyboard, mouse, joystick, and graphics as well as high level modules for tasks such as video playback.
python,snake game python,python snake game,python pygame snake,snake game,snake game in python,snake,snake game with python,python snake tutorial,pygame snake,pygame,python game,snake game python tutorial,python pygame snake game,python pygame snake code,python snake pygame,python tutorial,snake game python pygame,python pygame,python snake game code,snake game python code,python snake,snake python,create snake game in python
So we start with this template and what this template does is just load a window and when
you click on the small button here it just quits. So how does this work? Well first we load the
Pygame module like this so that module must be installed. You can install it with pip or depending
on your programming environment in PyCharm you can install it as a module. Then your entry point
is always main in which we create a new game object from the class game and we execute that.
So what does this game class do? Well it sets the variable running to true
and it initializes Pygame. You'll see here Pygame.init. Then it creates a window with this
line where it sets the width and height. So this is the width in pixels and height in pixels.
It instructs to use hardware acceleration. It sets the window title and again we set the variable
running to true and we already did that so we can essentially remove that. Then we have a render
function which just clears the screen. So in red green blue values everything is zero so it's a black
screen and this updates the screen. We have a quit function and this is the actual loop. So it starts
here. If it's not initialized it breaks. So while the variable running is true it goes over the
events. Now an event is for example anything the user inputs. So that can be a key press or a mouse
press. In this case you want to be able just to click the little cross. So if you load the program
you want to be able to click this cross. If that event occurs it'll set running to false and quit.
Now while it's in the running loop it calls the on render function so it repeatedly clears the
screen and updates the screen. Next we can load an image. So we can load an image like this. The
image should be in the same directory as your program. So in this case we have a cat image here
in the same directory as our python programs. Otherwise you need to specify the path, the
relative path or the hardcoded path. So you can load an image by calling pygame.image.load
and don't forget to add convert. So this loads an image into a sprite. I've named it cat image
and then you can draw it by calling the .blit method on your display surface and then specify
the image you want to use and the position. So this is the horizontal and vertical position.
If we run the program you'll see the position is at 0,0 in the left top. Now you can move it around
if you change these values. For example set it to 100 by 100 and that will move it by 100 pixels
on vertical and horizontal position. That can be anywhere on the screen just within the limits of
this window resolution. So if you see it's 640 white. So if you were to set it at 600 most of
the image will be outside of the screen. So you'll see you can't really see it now. So you want to
set it somewhere inside the screen. Now it's horizontal and then vertical position. So if we
were to set it to 0, the horizontal position would be 0 but the vertical would be 100 pixels.
So like this. You can set it anywhere you want just by changing those numbers and you'll see
in the next lecture that this can also be dynamic. Now we can make this position dynamic so we can
set an x and y position. In order to do that let's create an object. So the object is our player
which has an x position and a y position. We want to create a new object.
So we create a new player object from the class player and then we can say player.x
and player.y and we can increase that value each iteration. Now you'll see that when we run it
you'll see it's self.player because it's part of the class
and you'll see it's moving around. Now of course you can also do that for y.
So you'll see it's dynamic and you can even link it to keyboard input so that when you press keys
it starts moving around. Now you can fetch keyboard input using the function pygame.key.key
or getPressed. This function will return which key is currently pressed.
Then you can iterate over it like this. So we're fetching the cursor keys
and depending on which key is pressed it will output right left up or down.
So that's how you would do it. So make sure to call the getPressed
function and then you have the right left and up down keys. So now you can press those keys.
You'll see it doesn't stop so it just remembers the last key press. Now once something is pressed
you can start modifying the position of the image. So we can say self.player.x plus is one
minus one. You can do the same thing for the like this. So now we can move the image around
just by pressing the cursor keys. Now one thing to notice is that those brackets around it are
not necessary. So we can remove those and besides the cursor keys you can basically fetch any key
from the keyboard. And so we can say if keys k capital and you'll see we can take numeric keys
the a key, special keys, b key, c, backslash, currency, comma and basically any key on your
keyboard you can select from there. Now I'm using Visual Studio Code which has a recommendation
which is the same in PyCharm. If you use another program to write Python code you might not have
this recommendation list but basically you can fetch any of your keyboard keys. For example we
can take the a key and output a whenever it's pressed. So now whenever we press a you'll see
a appearing in the terminal. And this works for any key right so it can be also key for example
key b and then our program will start interacting for both keys. So you see when I press b, b is
appearing when I press a, a is appearing and the cursor keys still work. So you can fetch any key
off the keyboard. Now let's create a snake or a snake game. So I have added an image called
snake.png. So I'll change the image here to snake and our variable name cat doesn't make sense in
this case so I'll rename this as well. And now run the program and you'll see I use another image
format not jpeg but png and PyGame supports many different image formats regardless of
whether you have a portable network graphics png or a jpeg image or another type of image format.
So we have a little circle here that could be the start of our snake. Now one thing to know
with the snake game is that once you press a key it just keeps moving right you are not
when when you don't press the key it's still moving. And so in order to achieve that we can
create a direction variable. So I'll name it d for direction and depending on the direction it
just will keep moving. So instead of immediately moving the image position it will change the
direction. So we can change this and we'll be setting the direction. So these numbers will
represent right left up and down and then based on the direction variable it will start moving.
So if it's equal to one it should go left if it should be able to go up as well.
Okay so this looks a bit cryptic but basically what we're doing is changing a variable,
the variable d for direction, whenever a key is pressed and then regardless of the input
it should start updating. Now one thing you'll see is that
actually this should just work so let me try. And you'll see it's moving automatically even
when I don't press anything but really really fast. And in order to prevent the
game from going too fast what nearly always happens is that they put a delay in there
in the running loop or in the game loop where because of the delay it's not going lightning
fast. So to do that we import the time module because the time has a function called sleep
which just delays the program. So we can say with every loop just delay a certain amount of seconds
so let's say we have one second delay and you'll see it's moving every second.
Now that might be a bit slower than you want so maybe 0.1 and you'll see it's moving around
might even do it like a shorter delay but you want a delay in there usually
in order to manage the game speed. So now you'll see it's moving just on very small micro positions
so it's moving pixel by pixel. What happens in the snake game is that it's using the old positions
and it draws the same image on the old positions and you don't want those to be overlapping
that's why you want to increase by the image size. Now in this case the image size is 44
which just happens to be the image size. Now you of course can take
any image size you want and you'll see now it's like super fast
you can delay it more
and you see it starts to move around. Next you want to store the old positions
and in order to do that we can just say create an array of positions part of the player class
and in this positions array we will store the old positions so
in every loop we know the snake is moving so we can just append to the positions
sorry layer and we'll append both the x and y position so that way we'll store the old positions
and then we need to draw that as well so instead of just drawing one position we want to draw every
position so we can comment this line and draw on the positions and if we run it you see we start
seeing a snake here however it does have an indefinite length so normally what happens in
the snake game is that the length of the snake grows with every apple it eats now in this case
there are no apples yet however we should be able to set the length so what we'll do is we'll set
the length of the snake for example the snake length is five and then we only draw or we only
append the amount of times that are allowed so in this case one way to do it is just to
draw the last five positions so in this case we're drawing all of the positions
but you could say just only draw the last five positions another way to do it is to only allow
five positions for the snake so you'll see we add a new position each time so another way
you can do is to limit that which might be a better way than to draw because that way
the positions that we're drawing actually exist instead of having more positions that are not
round that doesn't makes less sense so it makes it more sense to just have positions
that are actually part of the snake and so we can say if the length of the positions
is smaller than the allowed length then append it so that will limit the length
however it only does that for five positions and then it doesn't do that anymore because
the length is greater than five so what you want to do in that case is to remove the old position
so remove the old position and in that and add the latest position so
so in this way so whenever the length of the snake is smaller than the allowed length
it adds that position the latest position to the snake to the list of positions otherwise remove
the first position from the list because that's the oldest position so remove the oldest position
from the list and add the latest position so that way the snake is only ever the size of the allowed
length if we run it let's say the snake doesn't get any bigger than five in this case because
that's the allowed length we set right so if we were to set that to a larger number let's say 15
you see that the snake grows to a size of 15 but it doesn't grow any longer than that
so that's an easy way to
limit the length of the snake and in the game of snake you always start with a length of one or two
maybe three probably not one because then you have just a dot right so maybe a length of three
or four is the the basic length let's say four so that could be a good starting point and then each
time we eat an apple the snake should grow next thing you want to do is to add some gameplay
so you want there to be an apple and in order to draw one you just define
one so that will create the image and let's also draw it so put it randomly somewhere on the screen
let's say 100 by 100 run the program and we don't see anything
and that's because we need to blitz not on the image itself but on the display
so change that to display and run it sorry let's display surface
run it and you'll see a snake image however we want to show the apple image
so now it's showing an apple on the screen
and this can be on any position right so it can be on 100 by 100
or any position now the position should be random it shouldn't just be hard-coded
so in order to get some level of randomness we use a module called random and specifically
a function called rent int now we can get an x and y position for our apple
so we can use rent int now can be any number so for example any number below 640
and any number below 480 now when we run the program
you'll see it needs the starting of the rent int so the numbers between 0 and 480 and between 0
and 640 if we run it you'll see it's randomly putting the apple everywhere so you want to set
the apple position but not every repetition all right not every time you draw the screen
so one thing you probably want to do is to create a class for our apple
with x and y then create an apple object and perhaps on the initialization phase
you want to set the position so self.apple.x and self.apple.y so we get a new position
when the game starts and we will use that position to draw now if you run the program
you'll see it's randomly put on a new position whenever the game starts next we'll want to
once something happens that when there's a collision so when the player or the snake
collides with the apple in order to do that we need to have a collision function
so i've created this one and this detects the positions between the snake x and y and the apple
x and y this should enclose the size factor so we just add it in the game class
and then we can start checking for a collision so whenever there's a repetition we can start
checking you can also check on the on execute function which may be better that
render is just for rendering the screen right it's better have that separation
so we can we have some game logic here so we can add it so if self.isCollision
we need the first x the first y i forgot a dot the second x the second y
and the size now in this case the size is 44 and if that happens we'll just output collides
now we can run the program and try to collide with the apple and you saw we had a collision
twice and so whenever there's a collision you want to set a new position for your apple
we copy this new position for your apple and we want the size of the snake to grow
so now we should have a basic snake game yeah so whenever we see it's growing
now it put it all the way on the edge which is not probably something you don't want
so you might want to limit the size a bit and you probably also don't want these random numbers
showing up right so we have 640 here twice and it's much better to just keep the
the size values of the game or in this case the screen
so let's add a game height and width and use those variables now make sure to not have a typo
there should be a self there this is part of the class now if we run it you'll see
we have the snake game however there are situations in which it doesn't collide
and that happens because the snake while it's put in a sort of grid based on 44 size which
is the size of the image the same is not applied to the apple right the apple is just
placed on a random position between zero and the height and the width
so what you can do is just to pick a number of your grid for example 10 by 10
and then that times the size of your grid so grid size in this case 44 and you can multiply that by
the grid size that's where you can never have the situation in which there is no collision
so should add self again because it's part of the class so now we can play the game and you'll see
it starts to feel like snake however there still is no losing possibility in the game
so while the snake gets longer and it starts eating the apples it's impossible to lose in
this game right now and so that's something you might want to add because at this moment
you cannot lose so in order to be able to lose you want at least that the positions
are greater than the or the length of the the minimum length of the snake
then what you can do is use the same is collision function however as parameters
we'll let it check if it collided with itself so we loop over the length
of the player of the snake and then we check for collisions and if there is a collision
it just is a game over so notice we use the index variable here until the player length
then we use the is collision function to check if the current position of the player
so that the head of the snake collides with any of the positions of the previous positions
now i've made the collision size a bit smaller otherwise there was some issue however if the
collision happens it will just output game over and exits so you'll see in both cases
whenever you have a sprite or anything in the game you can use the is collision function that
i've defined above here so this function to check whether there is a collision and if there is a
collision whether it's true you can execute some code so in this case there's a collision with an
apple and you execute some codes and in the case here there's a collision with itself the head of
the snake with any part of his body so if you run this program you'll see we can start playing the
game the snake gets longer let me just make it a bit longer and now i can make a collision and
you'll see it outputs game over and so you can also delete this debug output i've already done
that and you'll see that now we have the snake game because there's a way to lose in the game
so you can play the game yourself of course there's some tweaking you can do
for example you can output scores for the game
you might want to do other tweaking for example in the code base it starts to look like a really
long code and you'll see the code gets really long so you might want to split it up into smaller
functions so it's always a good idea to split up long code into smaller chunks into smaller functions
now in the beginning we kind of have that right we have some classes and some functions here which
is easy to read but then as you go on you'll see the the render function still it's okay
however the on execute function becomes a really large code so what you want to do is to split it
up into one or more methods or functions and in the case we are programming in a class so
so we can add a method here
for handling the game logic so something we could do
and we can copy all the game logic and put it in the game logic function
now of course we should call the game logic function down here
and make sure that the intention is still valid you just see we can still run the program
and we can still run the program however the code base just got a little bit cleaner
so you always want whenever you have a long piece of code you want to split it up
into more than one function so for example we can create a function snake logic where we
put in all the logic related to the snake and for these collisions are really related with the game
right so that can be the game gameplay logic now the naming is very important
when you're writing programs so you just remove that and put that here
so you'll see the code base becomes easier to read with smaller functions right you can just
look at it oh with the game logic it's doing the snake logic and the gameplay logic and of
course you can further split it up to have a really clean code base now we have some
code here for the events you can create a function for the event logic so we can copy all of this
stuff in the function handle events and make sure the intention is right and you'll see that now this
becomes a lot easier to read right so it still works you can still play the game
and however the code becomes a lot easier to read so whenever we have the on execute
method we'll see it just does three steps handle events game logic and render and then when you
need something specific like the handle events you can just grab the code you need or in this
case of the game logic you'll see it's the snake logic and the gameplay logic so depending on what
you need you can jump right to the function so whenever you have a big function or a big method
you should always split it up into smaller functions because it's much easier to understand
and to maintain if you have if your file starts to get very large so in this case the file is not
that large with 125 lines 124 but you can imagine as you write more code you get a file of like
thousands of lines and you can split your file into multiple files and for example start splitting
your classes into several files now pygame supports fonts so you can also show text inside your game
you can use system fonts depending on your operating system for example Arial, Alvectica or Verdana
call pygame.font.sysfont and you can specify which font you want and the size of the font
then you can render certain fonts so you'll see we call the .render function on whichever font we
have so in this case dialog font we call the render method with the text and also with the
color in red green blue values now these values are between 0 and 255 and the combination of
these three values of the red green and blue values make up the color and you can do this for
any of your fonts and make sure also to draw the font to the screen and you'll see that
it shows the text on the screen so you can download this example and you can also include
for example the score in your game so to show a font in your game as we've shown in the previous
code sample you want to load the system font with any system font you have and the size
then in your drawing function you want to render a certain text using that font
where you have their text and the color and then you display it on the screen so you'll see it
returns a surface or a sprite at a certain position and if you were to run this you would
see the text on the screen so right at the bottom where i put it of course you can put that text
anywhere you want however i didn't want it to be on top of the snake immediately when running the
game so that's why i put it at the bottom you can put it for example at position zero which is the
top of the screen however then it immediately overlaps