Snake Pygame Tutorial #1

Tech With Tim · Intermediate ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

This video tutorial series uses Pygame to create a basic version of the snake game, covering topics such as creating a snake object, implementing the main loop, drawing a grid, and handling user input. The tutorial is suited for intermediate level programmers with some experience in Python and Pygame.

Full Transcript

Hey guys, I just wanted to do a quick little intro before the intro kind of in this video series because I wanted to give you guys a bit of information. Pretty much when recording this, I wasn't sure how long it was going to take me to do all of the content and do all of the code for the snake game. So, I ended up just recording it all in one sitting. That means that I'm going to break this up into 15minute segments. It was about an hour worth of footage, so that should be four videos. And if the last video ends abruptly or whatever one you're watching, just know that it's going to start exactly where it left off in the next video, it's just because I wasn't sure when I was going to be ending it and splitting it up that I didn't really do like a formal conclusion or reintroduction in the next video. Just want to give you guys a heads up for that. And with that being said, enjoy the video. Hey guys, and welcome back to another YouTube video. In today's video, and I guess the next few videos, I'm going to be doing a tutorial on coding snake in Python. So, let's just go ahead and get a look at what this final product is going to look like. Um, so on like an XX grid, so whatever you want it to be. Um, you have a little snake moving around. There's a snack is what I want to call it that uh shows up. And as you collect it, it increases the length of the tail. And then obviously if you run into yourself, and I just did that by clicking the back key while I was going forward, um, it gives you a little error message here. here says you ran into your tail. Um, your length was nine dot dot dot whatever. Um, and then you can continue and play as long as you want. So, yeah, it's pretty cool. It's not super crazy hard to make. Um, but there is quite a bit of code for it. So, this is probably going to be a few videos. Um, anyways, what I'm going to be doing in here is I'm going to be coding everything object-orientated. I know that there's a much faster and easier way to do this. Um, but it doesn't really teach you that much. Um, this way you're going to learn a bit about objects, about classes, um, how we can kind of work with them and you'll see like how the flow of my program goes and you should learn quite a bit, especially if you're somewhat a beginner programmer. Um, what we're going to be using to make this is a module called Pygame. If you don't know about Pygame and you want to learn about it before you do this, I would recommend that. Um, if not, that's fine. But anyways, if you want to learn about that, I'll put a little card in the top right corner here. I have a tutorial series that goes through that. Um, and you can skim through that and learn a bit about Pygame before we get into it here. All right, so let's start coding. So, pretty much what I've done is I've just set up the flow of the program, all the classes, and the function just to remind myself what I need to write. Um, and while I'm talking here, it's probably a good idea if you guys copy this down. So, what we're going to have is we're going to have two main objects. We're going to have a cube object and a snake object. And our snake object is going to contain cube objects, if that makes sense. So each one of those little red uh I don't know squares that was moving around is a cube object and the whole thing is our snake object. Uh we're going to have a few functions here. Draw grid redraw window random snack uh message box and main. And in this first video I'm just going to go through and I'm going to code the two classes pretty well. Um and I'll get this draw grid function working a little bit of the main loop. And then we'll go into like the message box. Um getting more into some of the methods here in these classes in the next few videos. So let's get started with uh our main function here. And this is what's going to be our main loop. So essentially what I need for the main loop to start is we need to make a surface. So in Pygame to do this we do win equals Pygame dot display set mode. And then I'm going to set it uh let's see here. What do I want the height to be? I'm going to say width and height like this. Oops, bad spelling. And I'm just going to make a variable here called width equals height equals. And we'll just set this to 500 by don't have 500. Like so. Now, we need another variable. I'm going to set this as rows. Uh can delete this down here. I was going to do something, but I'll do that later. Uh this is how many rows you're going to have or rows or columns. Uh whatever. You can set this to whatever you want. Just make sure it divides 500 evenly. Otherwise, you're going to have like weird looking rows, uh if you know what I mean. So, I'm just going to set mine to 20. That's what I'm using in the other one. But if you want to make it harder, set it to something like 10. Um, and there won't be as much room for the snake to move around and the games will go faster pretty well. Okay. Next, what we need to do is we need to set up a snake object. So, I know that uh we haven't even created like anything in the snake class yet, but I'm just going to do s equals snake. And I'm just going to give it a position. So, in this case, we want to or a color, sorry, which is going to be red because red, green, blue, 255 for red. And then I'm going to give it a position. We're going to start in the middle. So I'm going to start at 10 10. Um, now let's move into our main loop. So I'm just going to say wow flag. Create my variable up here. Flag equals true. And then we're just going to start by doing a pygame tick. So pygame time delay 50 like so. And that's just going to delay us uh I want to say like 0.5 or 50 milliseconds um every time so that our program doesn't run too fast. I'm also just going to create this clock.tick. I'm going to put that at 10. And what I'm going to do is I'm going to create a clock object up here. Um and this is a built-in thing in Pygame. And what this is going to do is I'll explain in just one second once I finish typing it. Pygame. I believe it is. Oops. Time. like so. So, what this clock tick is actually going to do is it's going to make sure that our game doesn't run at more than 10 frames per second. Um, so that would mean essentially that our snake would be able to move like 10 blocks in 1 second. And again, we don't want it to be that fast. So, that's why we're also delaying um by like a few milliseconds here. If you put this too low um then again, it's going to move too low. You can play around with the speed. This is kind of what I found was the best speed. Um, and it may vary depending on what machine you're on. Although it shouldn't, it might. So, you might want to just change these numbers. Um, again, the lower this goes is the faster it's going to be. And the lower this one goes is the slower it's going to be. So, they're kind of uh inversely proportional like that. All right. Um, next, what are we going to do here? I'm just going to call redraw window. Oops. And I butchered that so bad. Oops. Redraw window. Like so. I'm just going to give it a surface which is in this case going to be win um that we've created up here. And for now that's all I'm going to put in my uh main loop here. And we'll move more into that once I start coding some other stuff. Okay. So now that we have our redraw window being called here. Um I'm going to go and I'm going to start coding our redraw window. Um so what this is essentially going to do is we first need to update the display. So pygamed display dot update like so. And we also need to um draw the grid. So we're simply going to do draw grid. We're going to pass it that same surface that we were given. Um and move on from that. We're also going to fill the screen. So when do fill. Uh in this case, I'm just going to use black. So it's 00 0. Um and there we are. That's all we need to do right now. But essentially, we're also going to need to draw the snake. Uh we're going to need to draw a few other things on the screen uh that we'll get to later. Okay. So draw grid. Let's move into this one. Now, uh what we need to do here is like draw a grid, which is pretty easy to do. Um so what we do is we're given rows and surface. So it probably be a good idea if I actually passed in the rows and surface. So I'm just going to global them here so that I can reference them. I think this is going to work. We'll do global rows and width like that. And here we also need to make these global just cuz I don't want to pass them in every time I draw a grid. We're just going to say width uh oops and rows. And this height variable is actually not necessary because we are just going to draw a square um like a square surface every time. So we can just make this the same. We don't need two variables for width and height which are going to contain the same number anyway. So global width and rows. I go here draw a grid given width rows and surface. So now we're going to put in well first we're going to put our rows or oops width row and surface like that. Okay. So that should be working. Now in here what we first need to do uh when we're drawing a grid is we want to figure out um how big each square in the grid is going to be. Cuz what we're going to do is we're going to just draw lines um going down and across. But we need to figure out where to draw those lines. So we have to figure out kind of like the gap between um each of the lines. So the way we do that I'm just going to create a variable here size between is equal to our width integer divided by our rows. Um this is just so that we don't get like large decimal numbers um because that we cannot pass into our uh draw line method in uh in Python. Okay. So now I'm just going to create x variable and y variable and I'm going to set these to zero. going say for L in range and this is just standing for line pretty well in rows like that. Now what I'm going to do is I'm going to increment my X by the size between and I'm going to increment my Y by the same. So Y equals Y plus oops size between can get rid of one of the spaces here. Oh what? Okay, there we are. And now we're simply just going to draw two lines. So to draw a line in Pygame, all we have to do is pygame.draw dotline and the arguments that that takes is a surface. We need a color. In this case, it's going to be white. So we do 255 255 255 for white. We're going to draw at x0, xw. And I'll go through this in just one second uh what this does. And I'm just going to copy this and draw one more and then explain um how this is going to work pretty well. Okay. So now we need zero y and w y like so. Okay. So what this is going to do is this is going to draw two lines for us every loop of this for loop. And these arguments here is the start position of the line and the end position of the line. So the first line that we want to draw is going horizontal which means we don't want to change the y value at all. Um so what we need to do is we need to find the x. Um, and then we're going to put y at zero. Uh, cuz we're going to be at the top. I think that's right at least. Oh, sorry. This list line is being drawn down, not being drawn to the right. I was getting confused there. Okay. So, we're going to change the x, but we're going to keep the y at zero. And then we're going to stay at that same x, and we're going to keep the y at the width of the screen so that we're going uh far enough down. And then same thing here. This one is going horizontal. Excuse me, I messed that up before. So, our x is always going to stay at zero. and our y is going to be what's changing um as we draw horizontal lines across the screen. I hope that makes sense to everyone uh how that works. Anyways, I'm gonna move on from that. And that's all we need for the draw grid uh function. So, let's just go ahead. I probably made a mistake here, but we'll run the program and just see if everything's working. Get name is not defined. Wind.fill. Ah, so I've called this win. One really needs to be surface like that. So, let's try now. And there we go. we get a nice little grid um on our screen like so. 20 x 20 grid. There we are. So now let's move into another uh function or actually let's start coding one of the classes here. So like I was talking about before, we're going to have a snake object which is going to contain a bunch of cube objects. So essentially what we're going to do is we're going to have a list of cubes. Um and that's going to be known as the snake body. So let's go ahead and write that in. Now um what I want to do for that is just create a list. So, we're just going to say body is equal to and then a blank list. I'm also just while we're already up here and creating a class variable, I'm going to create turns is equal to and it's just going to be this set of squiggly brackets here that we'll uh we'll get into in a bit. Okay. So, now that we're already in this snake function, what we need to do is we just need to define our um parameters here that we're passed in. So, we're just going to say self.color color equals color say self dot head equals cube which I'll get into in a second given the position say self dobody do append our head self head like this so what we're doing here now is we're saying okay so the head of our snake which is going to be important because we need to know where that is at all times so we can move accordingly is equal to a cube at the given position and the given position is what we pass in here as like the starting position of our snake. Um or we could create a new snake like we'd have multiple snakes moving around and anyways that's the position. Now we're saying we're going to append to the body um this head. So now this is in our list here. Um and then we can go through that list and we can draw things, we can move it, we can check things. We want all of our cubes to be ordered within this list. So that's why I'm putting that in first. Now I'm just going to give uh this one which is called d x is equal to zero and d y y which is equal to 1. So what this is going to do is we have a direction for x and a direction for y for moving our snake. So obviously these are going to be um a value like -1 1 uh or zero. And that's going to be the same for y and x. If y or x is equal to 1, then the other one's going to be equal to zero because you can only be moving in one direction at the same time. And this is just going to keep track of um what direction we're moving in. And we'll use this in the next function that we're going to code uh which is our move function. So moving is pretty straightforward um at least in terms of just if you have one object moving around the screen, getting it to go left, straight, right, but when you have the snake object, it has to turn at certain points. So when I click left, um, the rest of the snake is still moving forward. Once it reaches the point where the head turned left, then it has to turn left. So that's where things can get a bit complicated. [Music]

Original Description

Welcome to a new tutorial series! Coding snake using python and pygame. In this set of videos I will be showing you how to code a basic version of snake using python and the module pygame. This is suited for intermediate level programmers with some experience but anyone is welcome to follow along How To Install Pygame: https://www.youtube.com/watch?v=Okh-aKuHr7Q Download the code: https://techwithtim.net/tutorials/game-development-with-python/snake-pygame/tutorial-1/ Twitter: https://twitter.com/TechWithTimm Want To Support This Channel? Bitcoin: 1PbkAYLFaJBgjbKn2ptGyBz65xWN8hJgBU Ethereum: 0xdd42dbbdba60f7163fc7a840e189474b6e8bfcad Ripple: rD4arM9CVjQWqi8f1kxdpCgkCgEkqBgtud Please leave a LIKE and SUBSCRIBE for more content! Tags: - Tech With Tim - Pygame - Python Tutorials - Pygame tutorials - Coding snake - How to code snake - Coding snake in python - Coding snake with pygame - Snake game python - Python snake game - Python snake tutorial - Snake tutorial python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video tutorial series teaches how to create a basic snake game using Pygame, covering topics such as creating a snake object, implementing the main loop, and handling user input. The tutorial provides a comprehensive guide to creating a grid-based game with object movement and user input handling.

Key Takeaways
  1. Create a surface in Pygame
  2. Draw a grid in Pygame
  3. Create a snake object with movement functionality
  4. Implement the main loop in Pygame
  5. Handle user input for snake movement
💡 The tutorial provides a comprehensive guide to creating a grid-based game with object movement and user input handling, making it a great resource for intermediate level programmers looking to improve their game development skills.

Related Reads

📰
AI Testing Tools Are Easy To Buy But Hard To Trust
AI testing tools can generate more tests but not necessarily more confidence, highlighting the importance of trust in testing
Forbes Innovation
📰
Transform Business Operations with Robotic Process Automation (RPA) Services
Learn how Robotic Process Automation (RPA) services can transform business operations by automating repetitive tasks and improving efficiency
Medium · AI
📰
I Didn't Expect an AI Tutor to Beat My Favorite Online Course (But It Changed How I Learn)
Discover how an AI tutor outperformed a traditional online course, changing the way you learn new skills and subjects
Dev.to AI
📰
How to Talk to Your Database Using AI: A Practical Implementation Guide
Learn to use AI to interact with databases and simplify business question answering
Dev.to · Erwin Wilson Ceniza2
Up next
Advanced Tutorial NotebookLM Slides For Powerpoint
Russell Stannard (TTVideos)
Watch →