Make Pong With Python!

Tech With Tim · Intermediate ·💻 AI-Assisted Coding ·4y ago

Key Takeaways

Develops the game Pong using Python with game logic and scoring implementation

Full Transcript

[Music] hello everybody and welcome to another YouTube video in today's video I'm going to be showing you how to make the famous game pong in Python now this is a great project for beginner or intermediate programmers we are going to be using a module called py game to accomplish this however you do not need to know pame and the features we're going to use from it are very limited a lot of what we need to code out is the logic related to moving the ball around the screen having it bounce off the different paddles implementing score all of that type of stuff and you're going to learn a lot in this project if you are not say an expert python programmer already with that said let me give you a quick demo and then we'll actually start writing some code so in front of me I actually have the finished code for this project whenever I do a tutorial I code it out first and then I reference that code while I'm teaching it to you guys and all of the code that we write in this video will be available in the description anyways let me just run this here and then we can have a look at the finished product okay here we are so this is pong we have two paddles uh you can move one paddle with w and S and the other paddle you can move with the arrow keys and you also would be able to implement this as a single player game if you wanted to code like an AI for one of the paddles Which would be pretty easy to do you can see this is kind of the basics we have an implementation of pong and then of course there's scoring at the top and I've just made it so that when you get to 10 then the game is over now I'm not going to play through the entire thing but there you go that is the project and I'm going to show you how to make it so with that said let's get into the code after a quick word from our sponsor thanks to backtrace for sponsoring this video backtrace provides application monitoring as well as error and crash reporting for games we've all been there excited to launch a brand new video game just to be tormented by crashes bugs and an overall bad user experience back Trace wants to help limit that by providing a platform that gives game developers the best error and crash reporting with the most complete and helpful information back Trace works with any platform any engine and at any scale and provides 247 monitoring so you can retain more players and get better ratings back tray helps you fix issues fast by providing accurate call Stacks regression detection querying and analytics and integration with Microsoft teams Discord slack and more you can get started with back Trace today and manage up to 25,000 monthly errors with one month retention and 10 GB of storage completely for free check it out from the link in the description and thanks again to back trace for sponsoring this video all right so let's go ahead and get started the first thing we need to do is just set up our environment and install the P game package now again I want to reiterate here that you do not need to know pame for this tutorial I will show you the limited features from it that we are going to use now if you want to learn more about pame and make some more advanced games I have tons of tutorials on my channel so feel feel free to check those out you can probably just go on YouTube and search pame Tech with Tim and you'll see like 10 20 30 different videos all going through different P game projects all right with that said let's get this set up so right now I'm in Visual Studio code this is the editor I'm going to use for this video feel free to use whatever you want you can use the default idle from python you can use Sublime Text really doesn't matter I'm just going to use vs code now I'm using python version 3.9 you can use pretty much any version as long as it's above 3.6 other than that what we need to do here is open up a terminal or a command prompt and install py game now to do that we're going to type in the command pip install py game like that now I already have this installed so I'm not going to run it but for you guys run this command it should install py game now this command does not work sometimes if it doesn't work try the following Python and then you're going to do hyphen M and then pip install pame if that doesn't work try Python 3 hyphen M pip install P game and finally if that doesn't work try pip three install py game now if none of those commands work for you I have two videos one for mac and one for Windows I will put them up on the screen and they show you how to install pame for the respective operating systems okay so we now have py game installed we can actually start writing some code now we want to create pong so the first thing we're going to do here is just import pame we're going to set up what's known as a display so in pame we have a main kind of window or display and that's where we draw everything to to once we have the display then we'll imp Implement things like the paddle the ball the scoring uh handling Collision all of that type of stuff so I'm going to import pame at the top of my program and now I'm going to set the width and the height for my window now you're going to notice here when I'm coding everything out that I'm putting everything in variables this way our game will be dynamic and you can simply change the value of a variable and everything will just work in adjust according to that so rather than using kind of hard-coded values we're going to put everything inside of variables the variables for everything which will make it a little bit more complicated to code out however it's going to be really nice cuz if you want a bigger window or a smaller window or a larger paddle or whatever you just change the variable so for the width and the height I'm going to go with 7500 for right now by the way this is a way that you can declare uh kind of two variables on the same line in Python okay so now that I have that I'm going to set up my window so I'm going to put this in a variable called win in all capitals whenever I do something in all capitals I'm making a constant meaning that this variable is not going to change so to do this I'm going to say py game. display. setor mode and then inside of here I'm going to put a tupple and I'm going to pass the width and the height and I guess at this point in time it's a good idea to mention that you should have some familiarity with python of course you don't need to be an expert you can be a beginner but you should know things like if statements while Loops for Loops because I'm not going to explain all of the very Basics anyways to set up a window this is all we do py game. display. set uncore mode and then we pass a topple so just the brackets like this with width and height great now that we have our window we can make a caption for it so the caption is just going to be the title of the window and to do that we do py game. display. setor caption and for the caption I am just going to call this Punk okay so this will just be the title at the top of the window when it's actually loaded up so now that we have this what I want to do is Implement what's known as the main Loop of my program or the event Loop of my program which is actually going to display the window and then draw something onto it so I'm going to define a function here I'm going to call this Main and inside of this function I'm going to declare a few variables that we're going to use to actually uh kind of show the display and handle all of the events that are occurring so I'm going to make a variable here called run going to make this equal to true and I'm going to do a while loop here and say while run now whenever we have a p game uh game I guess Pi game program we need a main Loop and the main Loop is just a Loop that's constantly going to be running that's handling everything related to our game so it's handling Collision it's moving the ball it's allowing us to move the paddle so that's what this is right here so inside of this main Loop I'm going to write the following for event in py game. event. getet now this will get all of the events like clicking your mouse clicking the keyboard closing the window that's what this Loop is doing here looping through all of the different events that have occurred we're going to handle those events and then do something so in here the first event that I want to check is if we are actually quitting the window so I'm going to say if event. type is equal to py game. quit with all capitals for quit here then I'm going to say run is equal to false and I'm going to break out of this for Loop now what this is going to do is check if we hit the red button in the top right hand corner of our window so the close button if we hit that we want to stop the main Loop so we actually end up closing the program and then we want to break now outside of my while loop here I'm going to say py game. quit and quitting is just going to quit pame and close the program for us okay awesome now one thing I need to do here is right after I import pame I need to initialize it so I'm going to say py game.it you should run this whenever you import pame just directly below it it just initializes a few things that you need uh and we'll use this later or this will allow us to do some things later okay so here we go we have a basic program we have main we have run equals true we have our while loop here which is going to be the main event Loop inside of this we're checking all of the different events and then what I'm going to do here is call the main function so I'm going to say if name is equal to main then call Main now what this does is ensure that we are running this module to call this function so essentially if we were to import this module so the solution. piy file then what would happen is this would not run because the name of this would not be main now I'm not going to explain exactly how this works but it really just makes sure that you're only going to run this main function if you directly run this python file not if this python file was imported from another project or from another file okay uh hopefully that makes sense but when we do this we should see a py game window pop up there won't be anything on the window it'll just be a black screen but that's the thing we need to start out with okay so there we go we can see it says pong we have our pame window and when we click the X it should quit great there we go it quits okay so that's our starting thing now the next thing I'm going to do is Implement something known as a clock now a clock is going to regulate the frame rate of our game so that it's going to run at the same Pace on every single computer so I'm going to say clock is equal to py game. time doclock and then inside of here I'm going to say clock. tick and I'm going to pass this an all capital FPS variable which I'm going to Define up here as 60 now the FPS is the frames per second and when you put this inside of a wall Loop it makes sure that you cannot run faster than 60 frames per second or 60 ticks P per second which means that this wall Loop here is going to run a maximum of 60 times per second so that if you're on a really fast computer it's not going to be running quicker than if you were on a slow computer hopefully that makes sense but that's why we want the clock it just regulates the speed of this wall Loop now it's worth noting that if you're on a very very slow computer this wall Loop may run slower than the FPS that you're putting here this is simply limiting the amount of times it can run it's not making it run 60 times per second so on almost all modern computers it will run at least 60 frames per second or I guess exactly 60 frames per second but on a very slow computer you may run under this and so you may see some lag in your game if it's a really slow computer just wanted to note that because some people have mentioned that in my previous pame tutorials okay so now we have our clock and the next thing I want to do is Implement something to actually draw some stuff onto the screen so I like to handle all of my drawing in a separate function so it's really easy to see where I'm drawing everything so I'm going to make a new function here and I'm just going to call this draw and this is going to take in one variable which is going to be the window that we want to draw on now inside of here all I'm going to do for now is fill the window with a specific color just to show you how that works so I'm going to say wind. fill and then here I have to pass an RGB value now RGB is red green blue now I could just pass the RGB value directly in here but I like to Define all of my colors or RGB values as variables so I'm going to make one called White and this is going to be equal to 255 255 255 then I'm going to make one called Black and this will be equal to z0 Z okay so those are my two colors up here and what do I want to fill the window with well we are going to fill it with black but for now I'll just put white so we can actually see uh what's showing up now whenever we do some type of drawing operation in pi game we need to update the display manually and then it will actually do all of the drawing so when I do something like a wind. fill this is filling the entire window with white so it'll change the background color essentially to white but for this to actually happen I need to say pame do display not clear but do update now this will update the display and perform any of the drawing operations that we've done so maybe I've done a few other drawing operations I'm going to do all of those and then update the display and updating the display is kind of the most intensive part so doing the actual drawing does not take very long but updating the display where it applies all of the drawing that's going to take the longest so you only want to do this after you've done all of your drawing okay I'll continue to explain that in a second but for now inside of my wall loop I want to call this draw function so every single frame we're continually redrawing the window so let's call draw here and let's pass to it the all capital win which is going to be the window here that we want to draw on okay hopefully that makes sense let's run the program now and see if we're getting a white screen okay so notice we're getting a white background perfect that is what we wanted because we are filling the window with white now I'm just going to change this to Black uh because we actually want a black background I just wanted to show you how wind. fill works so now that we've done that what I'd like to do is implement the paddles so I want to have a paddle on the left side and a paddle on the right side and then I want to see the paddles actually be able to move when we hit the different keys on the keyboard so I'm going to make a class here and I'm going to call this paddle and the reason why we're going to do this is because we're going to have multiple paddles and we want their movement uh and different properties to be stored as an object so we don't have to kind of repetitively code this up now if you're unfamiliar with objectoriented programming I'll explain kind of the basic of what I'm doing here but I do have a ton of videos on my channel explaining objectoriented programming in Python okay so for the panel I'm going to say Define a knit now this is essentially what's going to be called when we initialize a paddle or create a new paddle and what I want to take in for the paddle is an XY width and height now our paddle is just going to be a rectangle one will be on the left hand side one will be on the right hand side and they're going to have different X and Y coordinates on the screen and we're going to change the y-coordinate based on where we're moving moving right so if the user presses the up Arrow key want to move it up if they press the down arrow key we want to move it down so I'm going to say self.x is equal to X self.y is equal to Y self. width is equal to width and self. height is equal to height now these are the attributes or properties of this paddle which means that each paddle I create will have different X and Y and different width and height uh corresponding to what we passed here when we created the paddle so there we go we have our initialization for the paddles now I want to write uh write a method on the paddles Which is essentially a function you can call on them called Draw now draw is going to do exactly what it says it's just going to draw the paddle now our paddle is going to be a rectangle it's going to have the color of white so let's define a class attribute here called color and let's just make this equal to White because this will be a constant it's not going to change so inside of draw I want to use the window to actually draw My Paddle on the screen so I'm going to say uh actually P game uh let's make sure the indentation is correct py game. draw and then not do Circle we want dot rectangle like that and I keep messing up my indentation so let's fix that and when I'm drawing a rectangle with python well this is how you do it py game. draw. rectangle and I need to pass to it where I want to draw it which is going to be the window right and then I need to pass a color well the color is going to be self do color that's going to reference this right here which is equal to White and then I'm going to pass a re re Angle now a rectangle is an X Y width and height so in P game when we draw something we draw from the top left hand corner so in pi game 0 0 is the top leftand Corner okay of the screen so if I draw it something like 1010 that's going to be 10 pixels uh sorry right and then 10 pixels down and then if we're drawing something like a rectangle for example the XY that we're drawing the rectangle at is the top leftand corner of the rectangle then the width and height is well the width and height of the rectangle based on the top left hand corner so you'll see what I mean here when I draw this but I'm going to do self.x self.y self. width and self. height that's all I need to draw the rectangle okay so now we have our paddle so let's create two paddles and let's draw them so I'm going to go here and I'm going to say my left paddle is equal to a paddle and I need to pass this in X Y width and height so for the X I'm just going to make this 10 so we'll be 10 pixels off the left hand side border of the screen then we're going to pass a uh a y the Y I want to be directly in the middle of the screen so we're going to say height which is the height of our window we're going to integer divide this by two just to get a whole number and then we're going to subtract this by whatever the uh height of our rectangle is going to be or the height of our paddle so I'm going to make a variable up here and I'm going to say paddle uh yeah paddle underscore height and paddle uncore width and this is going to be equal to just let me look at my screen here uh and 20 and I realize here that I probably want to go width first and then height second just to stay consistent with width and height up there so I'm going to say paddle width paddle height and we're going to make this 20 and 100 so that's the uh the values for our width and our height okay so we're going to use that now here and we're going to say paddle height / two now to explain to you why we want this let's just quickly open up paint and I can show you so let's zoom in a bit let's say this is our window okay now as I said here is going to be 0 0 now I'm drawing with my mouse so just excuse me but let's write this 0 0 now our height is going to be all the way down here so height is H this will be H okay so if our height is something like I guess we have 500 then this coordinate right here would be 0 comma 500 so the middle of this is going to be height over two right so we have H over two but the issue is if I start drawing my rectangle here I'm going to draw it like this because the top left hand corner is where I start drawing it from so what I need to do is draw the top left hand corner so that my rectangle will be perfectly Center so this will be the center of the rectangle hopefully that makes a bit of sense but to find this position here where we want to start drawing the rectangle from we need to know the height of the rectangle because if the height of the rectangle is say 100 then what I'm going to do is take whatever the height of my window is divided by two and I'm going to subtract half of this height which is going to be 50 and that will te tell me where I need to start drawing my rectangle so it's perfectly Center in the screen okay that hopefully again that makes a bit of sense we're going to take the height over two we're going to subtract the height of our rectangle over two and then that tells us the correct height to draw a rectangle at such that it's perfectly in the middle of the screen okay so let's close this here and let's now Implement that so this is going to be height over two uh minus paddle height over two okay I guess we already have that and then what we want for the width and the height is just going to be the paddle width and the paddle height now let's copy this cuz it's going to be very similar for our right paddle so here I'm going to say right panel except all I'm going to change is where I want the X to be because uh this is going to be different and I'm going to say this is going to be the width and then this is going to be subtracted by 10 subtracted by and then this is going to be the panel width like that now again the reason for this is that I actually have to go and paint to explain this if we want our paddle to be say 10 pixels off the right border okay then what I need to do is make the x coordinate be here right so let's say want this to be 10 kind of the gap between the right border then I need to account for the width of this rectangle as well as kind of the padding I want between the right border so what I'm doing is I'm taking whatever the width of the screen is which is going to be right here okay so this would be uh width and then zero this position so I'm taking the width I'm subtracting from the width this 10 which is the padding that I want and then I'm subtracting the width of the rectangle and that's telling me the exact x coordinate that I want to put this paddle at and then the height is going to be the same thing that's why I've left it the same okay hopefully that makes sense that is what we have for the right paddle and now what I want to do is draw the two paddles on the screen so to do this I'm going to pass to my draw function a list that contains both my paddles so I'm going to say left paddle and right paddle now I'm going to go to draw I'm going to take in paddles like that and I'm going to use a for Loop to draw both of the paddles so I'm just going to say four paddle and paddles paddle. draw and then we'll pass to this the window now why am I getting an error here indentation okay let's move that over by one and now we're good all right so the reason I'm doing a list is just because I'm going to do the same thing to draw both paddles so we can just do a for Loop and draw both of them and maybe some sometime down the future we add a third paddle a fourth paddle now we just pass it in the list it will draw all of them for us okay so let's now see if our paddles are showing up let's draw this and we got an issue py game. draw has no attribute rectangle uh am I spelling rectangle incorrectly let's see py game. draw. rectangle um hm ah my apologies guys this needs to be wrecked not rectangle uh that's actually how you draw the rectangle is with wck not rectangle okay let's try this let's run and there we go now we have our two paddles they are perfectly Center in the screen and they're at the correct x coordinates now we want to move the paddles so let's figure out how we can do that okay so to move the paddles we need to change their y-coordinate right move it up and move it down now we need a velocity to move the paddles at so essentially how much do we go up or down when the user hits a specific key so I'm going to add a velocity here on my paddle and make this equal to four now notice anything that's going to apply to all of my paddles I'm putting as a class attribute meaning I'm defining it here rather than inside of the initialization or inside of a method so I'm doing Val equal 4 now I'm going to implement a method on my paddle and I'm going to say Define move self and I'm going to say up is equal to true now what we're going to do here is call this method on the paddle and if I pass up equals true we're going to move the paddle up if I pass up equals false we're going to move the paddle down by the velocity so I'm going to do here is say self.y and then this is going to be plus equals and then the self. velocity but that's only going to be the case if up is equal to false so I'm going to say if up then we'll do something otherwise do this let me just copy this and then I will explain what's going on here okay so if self.y then minus equals self. Val so if we are going up and we want to move the paddle up now to move the paddle up we need to subtract from the y-coordinate whatever the velocity is right so we'll do that here otherwise though we need to move the paddle down so we'll say self. y plus equals whatever the velocity is so the yv value increases we're going down as the Y value decreases we're going up so this should now move the paddle up and down okay so now that we have this we need to actually call this but we're only going to call this when we are pressing the up or down arrow key now to do this we're going to have to get the keys that the user is pressing and then allow uh the paddle to move when they press a specific key now for this game I'm making it two- player so we're going to have W and S allowing the left paddle to move and then we're going to have the arrow keys allowing the right paddle to move now again you could Implement an AI for pong maybe we'll do a video where we'll Implement AI for pong let me know if you want a specific video on that but for now we're just going to do it with two players so I'm going to say that Keys is equal to pygame dokey. getor pressed and this is going to give us a list containing all of the different keys that have been pressed specifically it's actually going to give us I believe a map uh it's either a map or a list either way I'll show you how we can access and check if a key was pressed so I'm saying Keys equals pygame dokey. getor pressed now what I want to do is make a separate function that will handle moving the paddles for me because it's going to be a good amount of logic and I don't want it to kind of clog up my main Loop here so I'm going to call a function and this will be handle uh underscore paddle uncore movement like that we're going to need to pass to this the keys and we're also going to pass to it the left paddle and the right paddle so that we're able to move them okay so let's make a function now let's say Define handle paddle move let's take in our keys and let's take in our left paddle and our right paddle okay so inside of here we're going to check if the user is pressing the W or S key and move the left paddle and then the arrow keys and the right paddle so I'm going to say if keys and then this is going to be pame Dot and this is a capital Kore W notice this is a lowercase w so if we are pressing the W key then we want to move the left paddle up so we're going to say left paddle. move up is equal to true okay and then we'll say if keys and this will be py game. Kore s then we want to do the same thing but we want to move it down so left paddle. move and then not down equals true but this is going to be up is equal to false okay this is now handling the movement of our left paddle now let's copy this and do the same for the right paddle except we're going to do this with the arrow keys so just to note here when you want to check a specific key if it's a letter key or yeah I guess a letter key then you're just going to do a l lower case of whatever the letter is so a q w whatever if it's something like the shift key or the enter key it's usually in all upper cases so for the arrow keys we're going to say key uncore up or kcore up and for the uh down arrow key it's going to be Kore down in all capitals now all we have to do here is change this to be the right paddle and this one to be the right paddle as well okay so now this should actually be working uh handling our paddle movement so let's see if this is working by running our code okay so when I run my code now I can move my paddles but notice that my paddles actually go off the screen so now we need to implement something so we're not going to be able to move the paddle off the screen so to do that I just need to check to see that if when we move the paddle it's going to go off the screen or not if it's going to go off the screen when we move it then we're not going to let the user move it right so what I'm going to do here is say we will allow us to move the paddle if we are going up so if we're hitting the W key and the left paddle doy and this is going to be minus the left paddle. velocity uh is greater than or equal to zero okay so if left p.y minus the velocity because that's how much we're going to subtract from it when we move it is greater than or equal to zero which is the top of the screen then we'll let it move however if it's not going to be greater than or equal to zero so it's going to go off the screen even by a slight amount then we're not going to let you move it okay now let's do the same thing down here except we're going to have to check if you're going to hit the bottom of the screen so we're going to say and the left paddle doy this time we're going to add the velocity right so plus the left paddle. Vel we also need to add though the paddle height so I'm going to say plus left paddle Dot and this is going to be height like this and we're going to check if this is going to be less than or equal to the height of the screen so the reason we need this is because the Y that we're referencing is the top leftand corner of our paddle so when we're moving up it's fine to check that because that's the top of the paddle but the bottom of the paddle is the left paddle doy plus whatever the height of the paddle is right because that's going to give us where the bottom of the paddle actually is on the screen if we didn't have this then what would happen is we'd be able to move it all the way down until it was just barely off the screen because that's when the y-coordinate is at the very bottom so we need to add the height to make sure that we're not going to look like we're moving off the screen right and now we're checking if it's less than or equal to the height not greater than right because if it is less than the height then that's fine we can continue to move otherwise it's off the screen okay so that's what we're doing now we're just going to check the exact same thing here uh except for the right paddle for these ones so I'm just going to change this to be the right paddle and the right paddle and then same thing with moving down so let's copy this and put it here and now let's go right paddle right paddle and right paddle okay perfect so now this should make it so we cannot move off the screen because we're only going to move if we are not going to move off the screen okay so let's run this and see what we get and notice now that it stops at the very bottom of the screen and stops at the top of the screen let's just check the opposite and it is all good our paddles now do not move off the screen nice now that we've done that what I would like to do is draw a line in the middle of the screen just cuz I think that looks nice I want to draw a dashed line or a dotted line uh and I will show you how we do that so let's go inside of our draw function just need to reference my cheat sheet here because this is a a little bit complicated to do so I'm going to say 4 I in range we're going to start at 10 pixels we're going to draw up to the height and the increment for our for Loop is going to be height over 20 now the idea here is that I want to draw a bunch of rectangles to represent kind of a dashed or dotted line now I want the space between the different rectangles to be the same and I want the rectangle uh I guess height to be identical for every single rectangle so what I want to do is draw one rectangle not draw a rectangle draw another rectangle not draw a rectangle and kind of have a gap between each of them so that's what this for Loop is going to do and you'll see how I Implement that so I'm going to say if IOD 2 is equal to 1 then continue now essentially what this means is that if I is an even number then I'm going to continue so I'm going to skip this iteration and I'm not going to draw a rectangle otherwise though I will draw a rectangle and the way I'm going to draw it is the following I'm going to say pame do draw do re I'm going to draw this on my window the color is just going to be white so we'll draw it white and then the x is going to be in the middle of the screen so to do this in the middle of the screen we're going to say width over two but we need to subtract half of the width of the rectangle for the same reason we did that with the height when we were initializing the Y of the paddle so now if we're looking at it horizontally right if we want to draw right in the middle of the screen then the x coordinate can't be directly in the middle it needs to be whatever half the width of the rectangle Le is to the left of the middle so that it looks like it's directly in the middle so I'm going to say width over 2 minus 5 because the width of my rectangle here I'm going to make 10 actually let's see if that's what we're doing um I think yeah that's fine okay now for the y-coordinate I'm going to make this I now the reason I'm making it I is because I'm saying I want to have 20 rectangles on the screen right so when I say height over 20 that means that we're going to do this for Loop 20 times because we're going up to height and we're starting at 10 so we'll do it either 20 or 19 times either way though the reason I'm doing I is because we're going to be essentially picking what y value to draw at based on whatever the for Loop is currently at so we're going to start at 10 then we're going to skip one then we're going to be at whatever height over 20 * 2 + 10 is because that's how much we're incrementing the for Loop by every single time and so this will make it so our rectangles are evenly spaced out cuz that's how much we're incrementing the I by every single time so I'm using I for my height so width over 2 - 5 I then the width of my rectangle is going to be 10 notice this value here is half of the width right and then the height of my rectangle is going to be height over 20 because that's how much I'm incrementing the uh for Loop by so I need to make sure that's my height so that we're getting kind of the correct spacing for our rectangles I understand this a bit complicated this is how you do a dashed line there is some other ways to do it but they take up a lot more code so I'm going to do it in this way okay so let's just see if this is going to work now before we go any further let's draw this and notice now we get a nice dashed line or dotted line through the middle of the screen uh the top and bottom spacing might be slightly off but for me this looks fine now you could make this a solid line if you want that would be a lot easier but we're going to go with dash for now okay so I think that is all good now what I want to do is implement the ball so we want a ball that's going to be moving on the screen now let's just go into paint here and quickly discuss kind of some theory behind this because this is not trivial to do so we want a ball and this ball needs to move in two directions right it's going to be moving in the y direction and in the X Direction now it's also going to collide with paddles we'll talk about the Collision in a second but for now we want the uh the ball to move around the screen and to be able to collide with something like the ceiling now to move it as I was saying we need a velocity in the y direction and a velocity in the X Direction now we'll start by moving the ball just in the X Direction and based on where it hits the paddle we'll change its y velocity but just understand that we have kind of two compon components of movement in the X Direction and in the y direction and we're going to have to calculate what those velocities are and then move the ball by that velocity every single frame so hopefully that makes a little bit of sense but that's kind of the idea here behind the ball and I just want to explain that because that's what I'm about to start coding out so just like we had a class for our paddle I'm going to do one for the ball we don't necessarily need one but it's just going to make things a little bit simpler so I'm going to say class ball I'm going to say Define underscore uncore nit we're going to take in a self XY and a radius okay we're going to do a circular ball I know some pong games do a rectangular I guess you can't really call it Ball but a rectangular object moving around we're going to go with the circular one so for here I'm going to say self. xal x self.y equals y self. radius is going to be equal to radius and then self do xor Vel is going to be equal to Vel it's actually going to be equal to something called Max V which I will Implement in a second and we're going to say self. Yore V is equal to Z I'm going to implement my Max velocity so I'm going to say Max velocity is equal to and we'll go with five now the idea here is that I want to initialize the x velocity as whatever the maximum velocity is in the positive direction for our velocity we can have positive or negative and that will change the direction that we're moving right but I'm going to make this positive meaning it's going to be going uh actually to the right first I believe yeah should be going to the right anyways I'm initializing the x velocity as the maximum velocity meaning that we're going to be moving to the right at the maximum velocity when the program starts then once it hits the paddle we will simply reverse the x velocity and calculate the Y velocity based on where it hit the paddle at but the maximum velocity is telling us what the maximum possible velocity is in either direction so we'll always be moving at the max velocity in the X Direction but the y direction velocity is going to change depending on where we hit the paddle cuz we're going to have to change the angle at which we want to move the ball okay again I know this is getting a little bit confusing but hopefully that makes a tiny bit of sense now we're going to implement a method called Draw so very similar to our paddles we're just going to say self win and we're going to go in here and say uh this will be P game do draw Dot and then Circle we're going to pass our window we're going to have a color which we'll Define up here as just white again just doing this so we can very easily change the color and then we want a radius so we're going to pass the window drawn the color the radius and the X and Y position now I'm actually not sure if this is correct I think we have to do the X and Y before we do the radius so I'm going to do self.x self.y make sure that's in a tupple and then the radius comes after and I think that is correct perfect okay so now we have draw we have initialization and let's Implement move while we're at it because this is pretty straightforward so we're going to say Define move and all we do to move is we move the X by the x velocity so self doore X self. xcore Val sorry and then self.y plus equals the self. Yore velocity okay so that's how we move the ball uh this is our draw I think that is all good for now and the reason we can do plus equals is because if the velocity is negative then that will be equal to minus equals right it'll just move it in the other direction okay so now we have our ball we need to initialize our ball so let's go in where we have our left and right paddle and let's make the ball and say the ball is equal to ball now what's nice about the ball is that the X and Y position for it is the center of the ball meaning that if we want to put it in the center of the screen we can just actually calculate the direct middle and then place it there rather than having to do kind of the calculations here we did by uh subtracting you know half the width and that type of stuff so for the X and Y position of my ball I'm going to put it directly in the middle of the screen so I'm going to say width over two and then I'm going to say height over over two now the reason I'm doing two division signs here is because this is integer division it just going to give me the rounded division because I can't draw at a floating Point position all right so we're going to go height over over two and then lastly here for the radius we're going to make a variable we're going to call this ballor radius and for now we'll go with a radius of something like seven uh and we can of course change that later on if we want so let's now pass the ball under _ radius now we want to draw the ball so we're going to have to pass that to our draw function so pass the ball we're going to take in the ball here in draw and it's very easy to draw this because of the method we have we're just going to say ball. draw and draw it on our window great so now we have our ball this is the class uh and I think that's actually all we need for right now so let's run the program and see what we're getting and we got an issue let's see what the error is says uh maxv is not defined my apologies we need to add a self. maxv here rather than just maxv because I have to reference it from the class okay let's try this now and we got another issue it says ball object has no attribute maxvel ah we need an actual L here or an uppercase L rather than a lowercase one let's see if we get any other errors okay there we go so the ball is in the middle of the screen is not moving right now because we're not calling the move function or the move method sorry but once we call that we'll see that the ball actually starts moving on the screen then we need to handle Collision so let's move the ball to do that we're going to go to under actually where do I want to move the ball yeah it's going to do it right here I'm just going to call ball. move inside of my main Loop here and now we're going to be moving the ball every frame by whatever its velocity is okay so let's run this now and let's see and notice the ball is moving to the right of course it's going to go off the screen cuz we're not handling any Collision let's run it one more more time in case you missed it you can see the ball starts moving to the right now if we change the v y velocity it would move on an angle but for now we're just moving it in the X Direction so that's what's happened okay so now that we've done that we need to start handling Collision now I will admit this is not the easiest thing in the world to do but of course I'm going to try my best to explain it to you uh and you will have you know Collision handled by the time that this is done so let's go into paint again and let's just talk about how we're going to handle Collision first of all with like the ceiling and then we'll talk about the panles so we have this right here okay now let's say we have a ball and let's say it'sa trajectory is here okay so it's kind of moving up in this direction and this direction and the average of the components makes it so the angle it's moving at is here so if the ball hits here and it's going in this Direction with the Y all we actually need to do to make it bounce off of the wall is we need to kind of Bounce It Off on the exact same angle that it hit the wall at right so if you have like a wall like this and you hit like this you go here right pretty straightforward if you hit coming pretty straight on you're going to come out going pretty straight on as well if you head at a huge angle you're going to come off at a huge angle so that's how the Collision is going to work works either in the x or y direction now when we're talking about the ceiling all we actually need to do to implement this is we just need to change the direction of the Y velocity so here this y velocity would actually be negative because we're going upwards so to make it bounce off all we do is swap whatever the current y velocity is to the positive direction and then that moves us down hopefully that makes sense that's all you need to do to actually handle collision with the ceiling which we'll do shortly now that's the easy part collision with the paddle is a little bit more difficult cuz we're not going to do this in kind of a physics real way so let's say we have our two paddles here now in pong the way that the Collision Works at least my understanding of the way that the Collision Works is you're going to bounce the ball off of the paddle based on where the ball hits the paddle not based on the angle that it's coming in at now if the ball was coming at an angle like this if we're talking about real physics we should just bounce it off at the exact same Angle now the reason why we don't want to implement it like that is because that means our games are always going to be the exact same assuming you can line up the paddle you never can change the direction of the ball whatever Direction it hits the paddle out is the direction it's going to come off at so we need a way to actually manipulate that so we can have a game that's playable so the way that I'm going to do this is I'm going to figure out how to move the paddle based on its direction from the center of the paddle or sorry not move the paddle how to move the ball based on its kind of displacement or distance from the center of the paddle so if the ball hits here then I want to Bounce It Off on an angle like this okay if the ball hits here then I want to Bounce It Off on an angle like this if the ball hits in the direct center of the paddle then I want to bounce it like that so the further away from the center it is the higher the angle is I'm going to bounce it off on so we're going to you know have something along the lines of this and we'll calculate this using a custom function that'll show you how to write but that's the idea here with the ball so that's going to be more complicated to do but when the ball hits like here we're going to bounce it off pretty much in the center because this is almost directly in the middle right so we'll bounce it a tiny bit higher than that but that's kind of how we're going to do the collision with the paddles so let's say we have a paddle here okay this is the middle of our paddle this is going to be the XY coordinate and then we have a ball and this is the center of the ball so let's just go through some of the math here so we first need to figure out where the middle of this paddle is so can calculate the displacement between this and this okay so to do that we're going to take the y-coordinate which is right here so let's just call this y1 let's put a y1 here and we're going to add to this half of the height of the paddle so H over two okay so we're going to add H over two again I'm using my mouse here this is pretty hard but this is what's going to give us the middle so we can say uh this here is equal to M okay so this is m the middle now once we have M all we're going to do is subtract M from the y-coordinate of our ball so we can call this Y2 okay so we're going to take M and we're going to subtract Y2 now if this gives us a negative value that means we are above M if it gives us a positive value that means we are below it so once we have the displacement so we can call this D we need to figure out what the velocity should be in the y direction based on this displacement that's where it gets a little bit more challenging and I'm going to dive into that math in a second but for now we understand how to calculate the displacement once we know the displacement we just need to make it so that when you're at the maximum possible displacement uh in the you know up direction or the down Direction you're going to move at the maximum possible velocity whereas when you're at say a zero displacement you move at a zero velocity in the y direction okay uh hopefully I'm not confusing you guys too much I just want to give a quick rundown because now we're going to implement the Collision which as I've said is fairly complicated so let's do a function here and we're going to say handle uncore Collision now to handle the Collision we need the ball the left paddle and the right paddle Okay now what's nice is that we only need to adjust the Y velocity of the ball really that's the only thing we're going to do here but we need to handle it on the left paddle right paddle and the ceiling so let's start with the ceiling because that's the easiest so we're going to say if the ball dox or actually not X we only care about the Y because we're going up and down down we don't care about the Left Right Collision right now so we're going to say if the ball doy plus the ball. radius is greater than or equal to the height of the window then we're just going to say ball. Yore V multipli equal by-1 so simply going to reverse the direction now we're going to say l if the ball doy plus and actually minus sorry minus the ball. radius is less than or equal to zero than ball ball. Yore V this is going to be multiplied equal by -1 now that's actually all we need to handle the collision with the ceiling so let's just look at this one here this is saying if we're going to hit the bottom of the ceiling right so the height we're checking the ball. Y which is the center of the ball plus the ball do radius it's important you add the radius if you don't do that it's only going to check for uh collision with the center of the ball we don't want that we want it with like the edge of the ball which is the radius right so if that's the case then we just uh what is it change the direction reverse the direction now we do the exact same thing in the other direction except this time we need to subtract the ball dot radius not add it because we're checking up not down okay there you go we're now handling collision with the ceilings now after we check that we need to check if you're hitting the left paddle or the right paddle let's start with the left paddle so we're going to first check the direction of the ball because we're only going to see if we're hitting the left paddle if we're moving left right so if the x velocity is negative that means we're moving left left then we'll check if we're colliding with the left paddle otherwise there's really no point in doing that so I'm going to say if the ball Dot and it's going to be xcore velocity is less than zero then I'm going to check if we're colliding with the left paddle otherwise I'm going to check the right paddle so I'm just going to add a comment here so to check if the ball is colliding with the paddle we need to check both the x and y coordinate and check if the y-coordinate is within the range of where the paddle is on the screen so essentially if the Y value of the ball is greater than the yvalue of the paddle but less than the y-value of the paddle plus the height of the paddle that's going to tell us if it's where the paddle is on the screen essentially then once we check that so if the y-coordinates are correct if it's in the right range we need to check if the x coordinate is the same as the edge of the paddle that's essentially what we want to look at so I'm going to say if the ball. Y and we're going to say is greater than or equal to the paddle doy because remember this is the top leftand corner of the paddle and and the ball doy is this is going to be less than or equal to the paddle doy plus the paddle. height so that's the first thing that we want to check now after we check that we want to check if the x coordinates are correct now I could do this on the same line but just so it doesn't get too messy I'm going to do another if statement and I'm going to say if the ball. X and this is going to be I need to think about this for a second minus the ball do radius and we're going to check if this is less than or equal to the paddle dox plus the paddle. width okay let me check my cheat sheet to make sure I did this correct uh I think I did looks good to me okay so the reason we're doing this let's go to paint quickly is because we're checking the left paddle so if this is the paddle right here we know the top left hand corner XY is here and we know the edge of the paddle in terms of the x coordinate is going to be the X Plus plus whatever the width is so that's what we want to check now we have our ball this is the center of the ball so we need to account for the radius which is what we're doing so we're taking the ball. X we're subtracting the radius which gives us the edge of the ball and we're checking if that edge is less than or equal to this Edge right here if it is we're just going to change the direction of the X and that will then change how we move the ball off the pad okay so let's try this out let's go here and for now all we're going to do is change the x velocity we'll deal with the Y velocity later so I'm going to say ball. xcore V multipli equal by1 okay it's just going to change the direction so now we move from the left to the right okay so that is handling the Collision for the left paddle now handling for the right paddle is a little bit different so we're going to say if the ball. Y we actually can copy this for the Y so we'll do this except we're going to check paddle uh I keep saying paddle sorry this needs to be the left underscore paddle This needs to be the left underscore paddle This needs to be the left underscore paddle my apologies guys fix that so this will be left uncore paddle and then for here this makes it actually easier we just make this right paddle okay so right paddle and right paddle okay so now we've checked the Y for the right paddle now we need to check the X the x is a little bit different we're going to say ball. X Plus ball. radius and we're going to check if this is greater than or equal to the right paddle dox okay and if it is we're going to say ball. xcore V multipli equal by1 okay so the reason why this is a little bit different for the right paddle is because when we're moving to the right we're going to be checking the left edge of the right paddle and that is represented simply by the x coordinate of the right paddle because that's the top leftand Corner whereas when we're moving to the left we were checking the right edge of the left paddle which means we had to add the width now the reason we're adding the radius is because we're moving to the right so the radius is going to be to the right side that we're checking rather than the left whereas here we were subtracting the radius hopefully that makes a little bit of sense but I think this is going to be good to allow us to move the ball left and right on the paddles let's check this out and then we'll deal with the uh Y which is a bit harder okay so let's see this now it should bounce off the paddles okay so it didn't bounce off the paddle which means I made a mistake here let me check the mistake and I'll be right back all right so I found the airor this is kind of a silly one I'm not calling this function so I WR this wrote this function but I didn't actually call it so of course the Collision is not going to be handled so we need to call this now so after we move the ball uh then we'll handle the Collision so we'll say handle and then this will be Collision like that we're going to pass ball left paddel and right paddel okay fingers crossed hopefully this should work now let's run this and let's see if it bounces off there we go so it bounces off and notice that it doesn't really matter where I have the paddle it's just going to bounce off at the same direction I'll be because that's all we're doing right now now if I move the paddle it should just go off the screen and it does because well it's not going to collide with the wall we haven't implemented that great so there we go that is now dealing with the Collision now we want to deal with the Collision in the y direction again a little bit more complicated but we need to calculate the displacement between the ball and the center of the paddle and then determine the angle that we want to Bounce It Off on now we don't actually need to use trigonometry uh because of the way that I've implemented this but you're going to see the math is not uh not super straight so the first thing we need to do is calculate the middle y of the panel so we're going to say middlecore Y is equal to and then this is going to be the in this case it's the left paddle so the left paddle. Y and then this will be plus the left paddle. height divid two okay that's fine now the next thing we want to do is calculate the difference in y between the ball and the middle of the Y paddle or the middle of the left paddle sorry so I'm going to say difference in y is equal to this will be the middle y subtracted by the ball. Y now that we've done that we need to figure out essentially how much we need to divide this value by to determine what the velocity should be so let's go back to paint here and let's deal with some more math so we have a Max velocity so let's call this V okay the max velocity is equal to I believe we had five okay that was a rough five that's a better five so let's just call this MX for Max velocity is equal to 5 now what we need to do is make it so when we're at the maximum possible displacement that's when we get this maximum velocity right so if we're hitting the very very edge of the paddle so we hit right here that's when we get a maximum velocity of five now when we don't hit this we want it to be a little bit less right so I want the velocity to maybe only be when we hit here so essentially how do we figure this out well what we need to do is figure out what value we need to divide whatever the distance is to make it so the maximum possible value we can get is five and then any other value we get will be smaller than five I understand this is a bit weird but we want it so that the distance or the displacement divided by some value gives us five when we're at the maximum possible displacement value and then when we're not at the maximum it gives us something a little bit less than five and as we get closer to the middle it gives us a smaller value that should reach zero so our range is 0 to 5 we need to take our displacement and then squeeze it in the values 0 to 5 hopefully this following a little bit um again not the easiest math in the world but we're going to have a maximum velocity of five okay that's our MV and our maximum displacement okay is going to be equal to half of the paddle so if we're taking the displacement from right here then the maximum possible displacement we can have is that the center of the ball is right here at the very edge of the paddle which is just going to be half the height of the paddle okay so our maximum displacement is height of the paddle / two so we have these two values and now we need to figure out what I'm going to call a reduction Factor and the reduction factor is how much we uh take the displacement between the paddle and the uh what do you call it and the ball and divide it by okay so now we also have D so let's write a variable D let's go back to this uh no I don't want a pencil I want brush okay D so we have D this equal to the diff distance between the middle of the paddle and the uh the B so the way that we figure this out is we say that our reduction factor which I'm going to call R so we want to have d over R is equal to MV when when specifically D is equal to MD so when the displacement is equal to the maximum possible displacement that we can have and we divide it by R we want to get the maximum velocity that's what I'm saying here now it doesn't matter if it's positive or negative because we'll get either the maximum positive or maximum negative velocity anyways that's kind of the equation that we have now fortunately we can solve for r because we have a value for D and MV now once we solve for R we just use r as the reduction factor and then that's going to give us what we need for the velocity for our ball so if we plug in D which is going to be MD which is just H over2 then we have H over 2 over R is equal to MV and we know MV which is five now H over2 is going to be variable based on the height of the paddle but I think we actually know that this value is 50 anyways I'll show you how we solve just using the variables so if we have H over2 over R is equal to 5 and we're looking for R then what we need to do to actually solve this is we need to do the following we're going to have to flip R and H over2 so we're going to say R over H over 2 is equal to 1 over 5 okay because what we do to one side we need to do the other side then we're going to take H over2 and we're going to multiply by the one right here so we're going to have H over2 over 5 is equal to R okay so it's going to be whatever the uh the distances the maximum distance over five in this case it would just be our Max velocity so that could potentially change is equal to R and then we take in the future whatever the displacement is divided by R and that gives us the value I know that was a lot I'm sure it's not 100% clear once I write this maybe it'll make a bit more sense but I just want to go in and try to explain how that works okay so now I'm going to calculate the reduction Factor so I'm going to say reduction factor is equal to this is going to be left paddle do height / two okay divided by two and then we're going to take all of this and we're going to divide this by the maximum velocity of the ball so I'm going to say ball. maxor Vel like that okay now we have the reduction Factor now that we have this we need to use this to calculate the Y velocity so I'm going to say the Y velocity is equal to the difference in y divided by the reduction Factor okay so now this is going to squeeze our difference in y within the range of -5 to 5 which is now going to allow us to up update the Y velocity so now you can say B yv is equal to the yv okay now it turns out that we do the exact same thing here with a few minor changes uh inside of this function we just need to change left paddle to be right paddle and it will give us the exact same result now there's there is a lot of repetitive code here uh theoretically we could maybe write a function to calculate this for us but for now I'm just going to put it inside of here because I think this is fine so let's run this now and see if it's working so if I look at this paddle here it's actually bouncing in the incorrect Direction okay I need to fix that yeah same with the other paddle so it's giving us the reverse of what it should be uh so I'll show you how we can fix that but it is bouncing on an angle which is what we want so the reason it's giving us the reverse of what we want is essentially because we just need to multiply the Y velocity by negative 1 we're going to say netive 1 by y velocity and -1 uh multiplied by y velocity how did I mess that up twice okay let's Rewrite this1 multip by y velocity now it should give us in the other direction you can look at the math and you'll probably figure out pretty quickly why it's giving it to us but it's because we're taking the middle Y and subtracting from ball y if we do ball Y and subtract by middle y then we don't need to do this but I think this makes more sense so that's why I'm doing it this way anyways let's try this let's see what we get okay now it's bouncing in the correct direction nice that's what we wanted notice when it hits the edge of the paddle it's going to bounce more down okay there we go we got it to Bounce Down nice awesome and it bounced off the ceiling completely fine so this is working as I anticipated now what I want to do is I want to make it so when it goes off the screen we actually increment some type of score and display that okay so let's get started on that our Collision is working properly as you notice the closer we got to the center the more the ball bounced off straight and the further away from the center the more we had an angle that's why I was doing all this math that's kind of how that works okay so now we want to implement type of score so to do that we need two variables we're going to say left score and right score so the left score will be equal to zero and the right score will be equal to zero as well now to check the score we just need to see if the ball moves off the left or the right hand side of the screen so I'm going to say if the ball. x is less than zero then this means that the right player scored because it came off the Le hand side of the screen so we're going to say rightor score plus equals 1 L if the ball. x is greater than and this will be the width of the screen then we are going to say left score plus equals 1 now that we have both of scores we can pass those to the draw function so we can say left score like this and right score and then if I go to my draw function I can now take in the scores so we'll say left score right score and we want to draw them on the screen now to draw them on the screen I need something like a font right I need to actually draw text on the screen so to do that I need to write a font so to make a font you can do the following score uncore font is equal to py game. font. S font like that now this takes in the type of font which I always just use as comic Sands and then the size of the font which I'm going to go with as 50 feel free to modify these values but this is the font you want and this is the size of the font and now you use this font object to actually render text that you put onto the screen so inside of my draw function here I'm going to use score font and I'm going to draw this uh at the top just so that the ball can be drawn over top of the score so whatever I draw first will be drawn first meaning that whatever I draw last is going to be on the very top so I want to draw the ball last that it will be over top of my score okay so the way that I do this is I say the left score text is equal to the score font and then I call render and I pass to this the text that I want to render which is going to be an F string containing the left score okay and then I'm going to pass one and I'm going to pass the color which is just going to be white now one stands for anti-aliasing just always make this one okay so you do the text anti-aliasing the color and that's what we have now F strings allow you to just embed Expressions directly inside of a string so I'm just doing the score here directly inside of the string to avoid having to convert it to a string using the string function now for the right score it's going to be the exact same thing except right score okay so now this actually gives me a drawable object now that I have a drawable object I want to draw it on the screen so I'm going to say wind. blit and I'm going to blit the left score text and then I need to pass an X and Y location for it now I want the left score text to be exactly in the middle of the screen on the left half of the screen so this is actually fairly easy to do but I'm going to say width divided by four not divided by two because I'm trying to put this on kind of the first quarter of the screen or the first half of the screen in the center so I'm going to say width over four and I'm going to subtract this from the left score text. getor width over two okay and then for the height I'll just pick a height of like 20 pixels now we'll do the exact same thing for the right text and then I'll explain why I'm doing this calculation so this is going to be right score but for the right score I want this to be in the middle of the right hand side of the screen so I actually want it to be 3/4 of the width of the screen right that's the middle of the right hand side of the screen and then I'm going to subtract that from the right score text. get width over two so for this I'm going to do width and I'm going to multiply this by three over four okay so hopefully that makes sense I think I can actually just do it like this and say width multiplied by 3 over four and then minus the right Square I get underscore width over two that should work properly so to go to paint to quickly explain this again if we want this to be in like let's do this we have half the screen the middle of this half is right here okay so this is width over four that gives me this exp position then I have my text now if I draw my text here it's going to go like that I don't want it to be like that I want it to be directly in the middle so I need to draw it like this so I'm going to take half the width of the text and subtract that from this position that gives me the top left hand corner for where I need to draw now exact same thing over here this is three over four width right so I take that subtract it from half of the width of the text I'm drawing and I get it directly in the center of the screen okay and of course this is how you get the width of the text object you just use get width perfect so that should now draw my score so let's see if this is going to work uh okay wait I think I'm in the python terminal here let's just quit that yes okay let's rerun and notice now that if we score this goes up and it's going to continue going up because I don't reset the ball so I need to reset the ball but you can see that is indeed drawing in the middle of the screen and it's changing uh based on what the number is right okay so how do we do this now so once the ball goes off the screen we need to reset the ball so I'm going to put a method on my ball just called reset so I'm going to say Define reset and what I need to do in here is I need to reset the Y velocity as well as the x velocity and then change the X and Y position to be originally what it was set so I'm going to add some new values here I'm going to say this is equal to self. originalx and this is equal to self. original y now let's make those lower cases so the idea here is when I initialize my ball I'm going to store what the original X and original y value was in a separate variable so that's how you do this here and then I'll change the X and Y as I go through the program but I'm storing the original X and the original y so I can reset the X and Y to be equal to the original X and original y when I reset so I'm going to say self.x is equal to self. original X okay and then we're going to say self.y is equal to self. original y then I'm going to reset the Y velocity to be zero okay and I'm going to say the self.x velocity multiplied equal by1 now the reason I'm doing this for the x velocity is if I go off the screen going left then I want the velocity of the ball to be hitting my opponent when the ball resets okay now same the other way around if I go off the screen going right then I want the ball to go left and hit my opponent's paddle first you could change this if you want by just making it equal to the max Val or not even changing the XV you could do that that'd be fine but I'm just going to reverse the direction so if it just went off your screen then it will go to the other person hopefully that makes a little bit of sense that that's what I'm doing with the x velocity here okay so that's reset for the ball so now uh if they score we want to reset so I'm going to say ball. reset and ball. reset okay easy enough let's try this and see what happens okay so let's score and now notice it comes off and hits my opponent's paddle so that's what I'm trying to do just to give my other player some time to recover so if we score now it comes off on that side okay let's score on the other side and see if our score goes up okay score goes up and then it comes back to me all right now again you can change that if you want but that was kind of my idea here now one thing we could do is also reset the paddles uh when we score that might not be a bad idea uh for now I'm not going to do that but I think I've showed you how you would go about doing that just implement the same logic on the paddles and then call reset on left paddle and right paddle okay nice now that we have that the last thing I need to do is handle winning the game so if the left player wins I want to say you know left player wins if the right player wins I want to say right player wins so I need to first come up with a score that I want to end the game at so I'm going to say the winning underscore score is equal to 10 and now we want to check if either player has a score of 10 after we increment the score so I'm going to go here and I'm going to say if the left score is greater than or equal to the winning score then we want to do something and I'll say l if the right score is greater than or equal to the winning score then we want to do something now the first thing that we want to do is we want to say ball. reset okay and we want to say ball. reset here as well now I actually want to reset the paddles if someone wins because we're just going to play a new game so let's actually implement the reset uh method on the paddles cuz I guess we're going to need that anyways so let's go to our paddles and in the same way that we did this for our ball we're going to say self. original X and self. original Y and then we'll just Implement reset so Define reset self self.x is equal to self. original X and self.y is equal to self. original y okay paddle reset done very easy so if one player wins we want to say left uncore paddle. reset rightor paddle. reset and same thing okay nice left paddle reset right paddle reset now the thing is this is pretty repetitive uh so we could try to wrap this in a way where we're only going to write this code once in fact let's actually do something I'm going to say reset actually I'm going to say one is equal to false and then inside of here I'm going to say 1 equals true okay and 1 equals true and then I'm going to say if one do this so this is just handling all our resets in one place now so we just have a boo in telling us okay did we win or did we not well if someone won then we'll do the reset and then inside of the left score and right score if statement we'll handle specifically what to do if the left player won and specifically what to do if the right player won now actually what I want to do is just put some text on the screen show it for 5 seconds saying Hey Left player one right player one and then just immediately reset the game so to do that I'm just going to render some font so I'm going to say say win text is equal to uh and actually yeah we could just do win text we could say left player one exclamation point we can say wincore text is equal to right player one so now that we have this in a variable what I can do inside of one is I can use that variable to render text depending on who actually want so I can say my wincore yeah I'll say win actually let's just say text is equal to and then this is going to be the score font we could make a new font I'm just going to use the score font do render we're going to render the wind text one and then we're going to render this in white and we're going to blit this to the middle of the screen so I'm going to say win in all capitals do blit and I'm going to blit the text and then I'm going to blit this at when or I'm going to blit this at height no at width over two minus the text. getor width over two and it's going to be at height over two minus and then this is going to be the text. get height over two okay so we're centering in the uh X position and the Y position then I need to update the display I'm going to say py game. display. update and I'm going to say py game. time. delay 5000 and 5,000 is going to be 5 Seconds this is the number of milliseconds that I want to display the program by let me run through this because I know I went quickly we're saying the text is equal to score font. render so we're just rendering a drawable object the text we're rendering is whatever we put here just so we're not repeating a bunch of code and doing this in both places right I'm rendering this with antiel saying one the color white I'm then blitting this directly in the middle of the screen I've talked about how we do the middle calculation many times so I won't go through this again we're going to update the display so that it instantly shows then we're going to delay by 5 Seconds we delay by 5 Seconds then we reset everything now when we reset we also need to reset the score right so we're going to say left score equals 0 and right score equals z and I think that's actually all we need to do for reset then the game will restart and everything will just work as expected then when you hit X of course the game's going to end all right so I think that's actually all good that should really wrap up the program let's run this though and give it a test and see if it's working so let's just see if we can score 10 so I'll just kind of let this run and then once it's done I'll be right back and confirm that it's working okay so we're at a score of nine let's see now if this is going to work okay it says right player one perfect and then it should restart the program let's see perfect restarts awesome okay so that is pong we have finished the game now as I promised hopefully you learned a lot in this video uh I just covered Collision we covered some more advanced math drawing you know kind of separating the program out and how we have different functions handling different stuff uh yeah I think this is a fun program again great one for beginner or intermediate programmers and I am going to end the video here I will end off by saying that I do have a course programming expert. you can check it out from the link in the description use discount code Tim this course is designed for beginner or intermediate programmers looking to get better at programming this teaches programming fundamentals object-oriented programming Advanced programming software engineering tools all kinds of great stuff check it out from the link in the description it's definitely a great resource especially if you guys want to support me with that said I will end the video here I hope you guys enjoyed if you did make sure to leave a like subscribe to the channel and I will see you in another one [Music]

Original Description

Welcome back to another video! In todays video I am going to be showing you how to make the famous game of Pong in Python! This is a great project for beginner or intermediate programmers. A lot of what we need to code out is the logic led to moving the ball around and having it bounce off the different paddles and implementing the score. If you are not, say an expert Python programmer already, you're going to learn a lot from this project! 💻 Thanks to BackTrace for sponsoring this video! Build better games with less bugs today for FREE by signing up for a developer account: https://hubs.la/Q012hTT00 💻 ProgrammingExpert is the best platform to learn how to code and become a software engineer as fast as possible! Check it out here: https://programmingexpert.io/tim and use code "tim" for a discount! Code In This Video: https://github.com/techwithtim/Pong-Python Fix Pip (Windows): https://www.youtube.com/watch?v=AdUZArA-kZw&t=204s Fix Pip (Mac): https://www.youtube.com/watch?v=E-WhAS6qzsU ⭐️ Timestamps ⭐️ 00:00:00 | Overview 00:00:48 | Pong Demo 00:01:40 | Sponsor 00:02:38 | Pygame Install 00:04:16 | Pygame Setup 00:12:57 | Creating The Paddles 00:21:28 | Moving The Paddles 00:32:14 | Creating The Ball 00:35:52 | Moving The Ball 00:39:07 | Handling Collision 00:58:54 | Implementing Score 01:06:33 | Winning The Game 01:11:38 | Conclusion ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️ 👕 Merchandise: https://teespring.com/stores/tech-with-tim-merch-shop 📸 Instagram: https://www.instagram.com/tech_with_tim 📱 Twitter: https://twitter.com/TechWithTimm ⭐ Discord: https://discord.gg/twt 📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/ 🌎 Website: https://techwithtim.net 📂 GitHub: https://github.com/techwithtim 🔊 Podcast: https://anchor.fm/tech-with-tim 🎬 My YouTube Gear: https://www.techwithtim.net/gear/ 💵 One-Time Donations: https://www.paypal.com/donate?hosted_button_id=CU9FV329ADNT8 💰 Patreon: https://www.patreon.com/techwithtim ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼
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

Related Reads

📰
Antigravity has no task queue. Meet @trigger, its real async primitive
Learn about Antigravity's async primitive @trigger and how it replaces traditional task queues in the Python SDK
Medium · Programming
📰
The AI Senior Dev Dilemma: Am I Coding or Just Prompting?
Senior devs face a dilemma in AI-driven development: are they truly coding or just prompting AI tools, and what does this mean for their skills and career?
Dev.to · Agentic Architect
📰
The Python Skills AI Still Can’t Replace in 2026
Learn the Python skills that AI still can't replace in 2026, focusing on security, architecture, and judgment
Medium · Programming
📰
The Python Skills AI Still Can’t Replace in 2026
Learn which Python skills AI still can't replace in 2026, including security, architecture, and judgment
Medium · Python

Chapters (13)

| Overview
0:48 | Pong Demo
1:40 | Sponsor
2:38 | Pygame Install
4:16 | Pygame Setup
12:57 | Creating The Paddles
21:28 | Moving The Paddles
32:14 | Creating The Ball
35:52 | Moving The Ball
39:07 | Handling Collision
58:54 | Implementing Score
1:06:33 | Winning The Game
1:11:38 | Conclusion
Up next
CodeAI at #ISTELive and their free lessons and learning space
Cool Cat Teacher
Watch →