Pygame in 90 Minutes - For Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everybody and welcome to another youtube video so in today's video what i'm going to be doing is going over pie game for beginners so as you can already see here i have a little game on my screen the purpose of this video is going to be to introduce you to the module called pygame in python i'm going to cover a lot of stuff in this video including sound effects images moving objects collision most of the fundamental and main things you need to know to actually create a game and we'll give you an idea of what we're going to be building it's nothing complex this isn't meant to be fancy again it's just meant to teach you how to work with this module and i figured we could do this kind of really simple two-player game to give you an idea of how everything works in pi game so you can see we kind of have two spaceships here they can move around the screen and i'm moving these with the same keyboard so i have wasd moving the one on the left and i have the arrow keys moving the one on the right and when i press the left or right control key that is actually firing bullets now there is sound effects i don't know if you guys can hear them i'll stop talking and hit it for a second so you might be able to hear that either way there is sound effects we'll be adding that in there and we'll show you how this works and you can see that once uh one of the enemies loses so they run out of health you can see that at the top it says boom yellow wins and even though i have these on the wrong side we'll fix that in in the original video anyways you get the idea this is the yellow spaceship this is the red spaceship really they should be on opposite sides for the tutorial we'll fix that anyways let's go ahead and get started but before we do i need to quickly thank the sponsor of this video before we get started i need to thank the sponsor of this video which is alco expert oligoexpert is the best platform to use when preparing for your software engineering coding interviews as the highest quality coding interview practice questions with over 115 practice questions detailed solutions in nine of the most popular programming languages a feature-packed browser-based coding environment extensive test suites and conceptual overviews and code walkthroughs for each and every problem algo expert is the best resource to use to ace your coding interviews algo expert also has a data structures crash course coding interview assessments and a brand new mock interviews feature i can highly recommend algo expert as a former customer myself and now an official instructor on the platform get started using algo expert today by hitting the link in the description and using the code tech with tim for a discount on the platform all right so big thank you again to that sponsor now let's go ahead and continue so the first thing we need to do when we're going to be working with the module called pi game is we need to install it on our computer now for some people this can be tricky it really shouldn't be that difficult but what you need to do is open your command prompt or open some terminal window depending on what operating system you're on if you're on windows you're going to open command prompt if you're on mac or linux you're going to open your terminal now this command may vary based on your operating system i'll go through all of the different variations but the first thing you want to type inside of your command prompt doesn't matter what directory you're in is pip install and then simply the module pi game go ahead and press enter that should install pygame in your python interpreter and your python environment then you should be good to go now for some reason this isn't working or when we get to the next step which is just testing our code and importing pi game you don't see anything happening try the following command pip3 install pi game so just add a three to the end of pip there uh oops i didn't mean to delete the three uh but pip three install pi game hopefully that one should work for you and if neither of those work for you then try the following python hyphen m pip install and then pygame like that and if this one doesn't work either then do the same variation so add python 3 hyphen m pip install pi game if none of those four commands work for you and you can't uh install pygame i'll leave links to videos in the description that show you how to fix your pip they're not directly called that but actually this will be perfect for this because they are how to install pi game on mac and windows respectively anyways let's continue now we have pi game installed we're going to head to some environment that we're going to write code in you can do this in the default idle so the thing that just comes with the basic python installation or you can use something like vs code sublime text whatever you want so i'm going to be using vs code this just makes it easy for me for me to run my code by pressing the run button up here but again feel free to use whatever you want you don't need to use vs code it doesn't matter what you use we're just going to do everything in one file anyways now that reminds me before we actually jump in we need to download some assets for this game so you saw i had a background i had those spaceships all of the stuff including the code for this tutorial is going to be available on github so i will leave a link in the description what you're going to need to do is download this assets folder mainly you can download the code file as well which will be uploaded here with the entire code for this video afterwards but to do that you're just going to press the link to bring you a page that looks like this you're going to press code and then download zip now if you understand how to use github obviously i don't need to tell you how to do this but downloading the zip file so let's actually just do it on here to make sure everything is going to be all good so i'll put that into my downloads then you're going to open up the zip folder you're going to go inside the interior folder you're going to grab the assets folder on windows i usually like to just cut it so ctrl x you can also copy it and you're going to paste it beside wherever your python file is so if you have your python file on your desktop i would recommend first of all you put it in a folder called you know pygame for beginners or whatever then just put this file beside it so that you have the assets folder and then whatever your main python file is is in the same directory that's really important so anyways do that and then we can go ahead and continue alright so apologize for the intro but let's get into this the first thing we're going to do now and notice that i have pi game tutorial and then i have my assets in my main.pi file obviously create a new python file and inside of that file you're going to type import pi game this is just to make sure that this is working so we're going to import pi game then we're going to run the code you can see it kind of pops up a little terminal right here and notice it says module not found no module named pi game now i'll fix that on my end but make sure you guys don't get this message if you get hey welcome to pi game or some little text like that you're good to go and you're ready to continue so i'll be back after i fix this for myself all right so i'm back you can see i'm now getting the message pygame 1.9.6 doesn't matter what version you're using hello from the pi game community and we're all good to go and get started now one last note here i'm just trying to cover all of the issues that happen do not name your python file pi game if you do that it will not work so just name it anything other than pi game very important okay now that we have that let's get started so first of all what is pi game well pi game is a 2d graphics library that lets you make little games it's actually really powerful i've created a ton of awesome projects using pi game and well it's pretty simple to actually set up the first thing that we need to do whenever we kind of start making a game in pi game is we need to make the main surface now i usually just refer to this as the window again you can call it whatever you want but in pi game everything that we're working with is usually referred to as a surface so you might hear me use that term but anyways i'm going to start in all capitals i'll tell you why in a second i'm going to say win equals pi game dot display dot set underscore mode and then inside of here we're going to put a tuple and we're going to put the width and the height that we want the window to be so it's usually good practice to define two variables above this that says width comma height and then is equal to whatever you want the width and the height of this game to be now i'm going to make mine 900 by 500 if you're on a really low resolution display this might take up like a large chunk of the display so feel free to scale these numbers down it doesn't really matter what you make the width and the height but it might affect what you want to make the dimensions of say the background or the images later on anyways we're going to say width height equals 900 500 win equals pi game dot display dot set under square mode and then inside of here i'm going to say in all capitals width height so i'm pretty much telling pi game hey let's make a new window that is of this width and this height and i've defined those both above the reason i'm using all capitals here is usually just good convention to define all of your constant values in capital so our window even though it may potentially change is fine to be in all capitals and our width and height those are constant they're not going to change so i'm making them all capital values all right so now that we have that uh let's actually start creating our first like pie game event loop and and having something pop up on the screen so usually what i like to do is i'd like to define a main function and inside of this function i'm going to put all of the code that kind of handles the main game loop in pi game so usually when you create a game you have a loop and this loop is doing things like redrawing the window checking for collisions updating the score whatever it may be and anyways we're going to put that inside of this main function right here so the first thing that we need to do is set up a while loop this while loop will be the game loop and this will actually let our game not just instantly open and then close so think of it as like an infinite loop and then we'll terminate it whenever the game ends so i'm just going to make a variable i'm going to say this is run it's equal to true then i'm going to say well run so until we set run equal to false or we break out of this loop this loop will keep running the first thing that you always do inside of your event loop in pi game is the following you say 4 event in pygame dot event like that and then dot get and inside of here is where you check for the different events that are occurring in pi game so don't worry about the fancy syntax but this is just getting us a list of all of the different events we're looping through them and then we can check what these events were and based on what they were that we can we can do something different so the first event that you usually check for is if the user quit the window so again i'll show you how all this works later and we'll go into more detail but just to get right into it we're going to say if event dot type equals equals and then pie game dot quit in all capitals what we're going to do is we're going to say run equals false like that and what this will do is end this while loop so effectively quit the game now at the very end of this while loop what we're going to do is say pygame.quit and this will quit pygame for us and close the window so hopefully this is clear so far but that's all this is doing we're getting all the events if quit is an event that occurs then we'll exit the while loop and we will quit now i'll show you what that event is in one second but let's continue so now that we have that uh let's actually go down to the bottom of our program and let's say if underscore underscore name underscore underscore equals underscore underscore main underscore underscore then we're going to call the main function now what this is doing for anyone who's confused is just making sure that when we run this file we didn't it's hard to describe this but it's making sure that we're only going to actually run this main function if we ran this file directly so in python if you're not aware you can import modules right so let's say i imported this file from another file well if i did that and i didn't have this if name equals equals main thing and i just had the main function you know in the main line like this then it would automatically call this and start running the game now we might not want that to happen and i only want to run the game if we run this file directly not if this file is imported from somewhere else so that's why i'm doing this you don't have to really understand what this means but the name is simply the name of the file and main is telling us hey this was the main file that was run that's the best way i can explain it they're going into too much depth but anyways enough of this we haven't seen anything yet so let's run it and see if anything pops up so we're gonna run and there we go we get some window like this right black window nothing just says pie game at the top now the quit event is when we press the x on this window so when i press that notice that boom we quit we're all good because we handled this quit event if we didn't do that it wouldn't have quit the window we would have had to force quit this application which obviously we don't really want to have to do so there we go we've got our first pie game window popping up but that was kind of boring now i want to show you how we can draw stuff onto the screen and how we can change the name of that window so usually what i like to do is i like to go up to the top of my program and say pygame.display.set underscore caption and i like to give it some name so here this will set that little name caption that you saw that said pie game window or whatever it was so you can set this to whatever you want for simplicity i'm just gonna say first game like that i'm gonna save i'm gonna go ahead and run this and notice that now it says first game where my mouse is here at the top left hand corner all right so now that we've got that let's start drawing some some stuff onto the screen and doing some more uh advanced stuff so the first thing i'm going to show you is how we can fill the screen with a specific color then we'll start drawing some rectangles and all of that and getting into the game so to fill the screen with a specific color this is pretty straightforward you're going to use the window so you're going to say win like that and then you're going to say dot fill and then you give this a color and it will fill the screen with this color now the question is how do we actually give this a color what do we type in for the color well in pi game all of the colors are rgb meaning red green blue so what you need to pass is a tuple with three values one value for red one value for green one value for blue if you're not aware of rgb the ranges of numbers that you can pass in here are between 0 and 255 inclusive so that means you can include 0 or 255. so i could say something like 255 255 255. funny enough this is actually white when you look at rgb because you have the most red the most green and the most blue so anyways i'm not going to actually pass in a tuple like this because this is kind of hard to understand that this is white i'm going to make a variable at the top of my program here in all capitals i'm going to call it white and i'm going to set that equal to 255 255 255. now instead of passing that i'm simply going to pass white inside of here so this way if someone else is reading my code they know that hey this is the white color that's what we're filling the screen with so let's test this out and run the program and why is it not working well the reason this isn't working right now is because we did not update the display so in pi game the way it works is we can draw a bunch of stuff onto the screen and you'll see that when we start doing that we draw all these different things but the display will not be updated it won't show the most recent things that we drew unless we manually update it so what we need to do is say pi game like this dot display dot update so now when we update the display after we fill the display it will update and will show us the white so let's have a look there we go now we are getting a nice white background you're welcome to mess around with the color and you'll see different colored backgrounds all right so there we go we have white awesome we are making good progress now the thing is i usually don't like to do all of my drawing inside of this kind of main game loop i usually like to have the main game loop handling like all of the collisions all of the logic in the game and then having some functions outside of that that handle specific things that i can easily call so what i'm going to do just to clean this up and make it easier because we're going to be drawing a lot more stuff than than just this is say define draw underscore window now inside of here what i'm going to do is just take as an argument whatever i want to draw now in this case we don't really have anything specific that we want to put on the screen we're just filling it with a background color so i'm not going to take any arguments i'm going to take these two lines of code right here place them inside of this function so let's do that and now right before inside this while loop before the pie game dot quit i'm just going to call this function so now every time i loop through this loop here i'm calling draw window and well this will draw stuff onto the screen so let's run this and there we go we get the same thing it is still indeed working awesome so that is great now the next thing we need to talk about is frame rate or essentially how do we control how much this is refreshing because if we have a look at this right now we have an infinite loop we have some event loop going on right here and then every time in the loop we're just drawing something onto the screen that's fine but right now we are drawing this white background as many times as we possibly can per second onto the screen it's pretty it's solely based on the speed of our computer right on my computer i have a pretty fast machine this is drawing probably hundreds of times per second in fact we could measure it but i would guarantee it's hundreds of times per second or even thousands now we obviously don't want that because that means on different computers our game is going to run at a different speed because it's based on how quickly this while loop is running so to control this we need to implement something called fps or frames per second so i'm going to define a variable up here i'm going to say fps and make it equal to 60 and this pretty much will define how quickly or how many frames per second we want our game to update at now most standard games that are not like your big aaa games are running at 60fps so we're going to go ahead and just implement a hard-coded fps of 60. so now what i'm going to do is i'm going to define a clock object in my main function here i'll discuss what this is in a second but i'm going to say clock is equal to pi game dot time dot clock and inside of my while loop i'm going to say clock.tick and then i'm going to put fps now what this is going to do is control the speed of this while loop so this will make sure that we're going to run this while loop right here 60 times per second no matter what unless our computer can't keep up with that speed in which case it will run as fast as it can so clock.tick is just ensuring that we never go over this capped frame rate of 60 which is good that's what we want it makes our game controllable and we know it's consistent on different computers so now if we run this actually let's just go up here you notice that nothing's going to change except just internally it's only running at 60fps okay so that's great but our game is pretty boring right now we have nothing on the screen so let's actually go ahead and implement some characters so i want to have two spaceships one on the left hand side of the screen one on the right hand side of the screen i want them to face each other and i want them to be able to move so let's tackle that next so what i'm going to do is i'm going to start importing the images that i'm going to use for these spaceships so i'm going to start by just saying yellow underscore spaceship underscore image and this is going to be equal to pi game dot image dot load and inside of here we're going to load the yellow spaceship image so if we go inside of assets we can see that we have five things we have spaceship yellow spaceship red space png that's the background and then two sound effects which we'll get to later again you can download this from the link in the description it's the github link so what we need to do is import these images right here so the red spaceship and the yellow spaceship we need to load them into pi games so we can draw them onto the screen so what i'm going to do at the top of my program is going to import os the reason i'm importing os is because i'm going to use os which is operating system to help me define the path to these images so these images are inside of the assets folder the assets folders in the same directory as our python file remember that's very important and then what we're going to do is we're going to look inside the assets folder and then look for these specific images so to do this we're going to say os dot path dot join this is just a thing that you can do in python the reason i'm doing this rather than just separating things with slashes is because depending on what operating system you're on the directory separator might be different so this will handle that for us but os.path.join i'm going to join the path to the folder assets with the path to the image so i'm going to say assets and then spaceship like that underscore and i guess we're doing yellowfirst.png so i apologize that it's hard to read let's actually just zoom out a bit so you can see this we get yellow spaceship image goes pygame.image.load.os.p asset spaceship yellow.png so let's copy that line i'm going to do the same thing now except instead of yellow we're going to do red so red spaceship image and now all we have to do is just change this to red because we have the red image right there so now we have our two spaceship images my formatters help me out here by putting them in a way that we can read them now what we want to do is draw these onto the screen so we can actually see them so before i get too complicated and talk about anything more let's just show these up on the screen or draw them on the screen and see what they look like so we'll say win.fill white remember i'm doing all my drawing from inside of this draw window and now i'm going to say win dot blitz now you use blitz when you want to draw a surface onto the screen so technically these images when they get loaded in by pygame are known as surfaces so we have to use blit to bullet them onto the screen now that's kind of a misleading explanation but you can kind of imagine that anytime you have text or images you're going to use blit to put them onto the screen but i'll go through that later so anyways win.lit we're going to say yellow spaceship image because that's our image right here and then i'm going to define the position on the screen in which i want to draw these images so remember that our screen is 900 by 500 so 900 width 500 height which means that i really should be drawing my spaceship within those dimensions so it shows up on the screen now i can draw it off the screen at like a negative coordinate or something but obviously that doesn't make much sense to do now another thing to note in pi game is that when you draw something onto the screen it draws from the top left hand corner in fact it's probably a good point in time now to talk about the pi game coordinate system so excuse me because i'm on a mouse this is going to be really rough drawing but let's imagine this is our pi game window you know traditionally when we look at like an axis right we look at a graph you would say that 0 0 is right here in the middle of the window now in pi game that is not the case we don't have that because we don't have these kind of coordinate systems so in pi game the top left or zero zero is the top left sorry so zero zero trying to do two zeros here with the mouse is the top left-hand corner which means as you increase your x you're going further to the right and as you increase your y you're going further down of course y being you know vertical and x being horizontal so if i wanted to be at the bottom of the screen and my height was 500 i would draw somewhere like 400 right and maybe that would put me you know like somewhere around here so just keep that in mind uh this is the coordinate system for pi game and when we draw an object in in pi game we draw it from its top left so it's consistent if i draw an image at let's say what would this be reasonably like you know 500 by 200 or something like that we will start drawing it from the top left so the uh the width of the object or the width of the surface will you know be going to the right if that makes sense and then the height will be going down so even though it's at this position we're not drawing it from the center we're drawing it from the top left of the image so keep that in mind okay now we went through that so let's draw this image so we want to draw the top left of the spaceship where we're picking where we want to put the top left of the spaceship so in this case let's just put it at like 300 100 just to see what it looks like and in fact for now let's just draw the yellow one so we're going to go ahead and draw this and that's greed okay so it's taking up a good chunk of the screen this is obviously too big we're going to have to shrink this down but there you go you can see the spaceship showing up on the screen awesome now keep in mind though if i were to draw this spaceship before i were to fill the screen so if i do something like this then what do you think is going to happen so i go ahead i draw the spaceship then i fill the screen with white and then i update what do you think is going to happen i'm going to run and we don't see the spaceship the reason we don't see the spaceship is because we drew the spaceship before we filled the screen so the order in which we draw things matters and we can draw over top of something that's totally valid that happens all the time okay so just keep that in mind so now we have the yellow spaceship and what we want to do now is resize this spaceship so it's a bit smaller so we should pick the dimensions we want to resize it to then we also should rotate this spaceship so it's facing the correct direction so i'm actually going to start by resizing this image and then i will rotate it so i'm going to say yellow underscore spaceship like this and this is going to be equal to and then i'm going to resize and rotate this image in the same line i'll show you how to do both of them so in pi game to resize something you're going to say pie game dot not image sorry dot trans nope dot transform like that dot and then scale and inside of here you're going to pass the image that you want to resize so we're going to pass yellow spaceship image like that and then you're going to pass the dimensions that you want to resize this to so our spaceship was pretty wide it wasn't that tall we could look at the aspect ratio to determine what we want to resize this to but i'm going to go with 55 by 40. so 55 width and 40 height if we consider that the dimensions of our screen are or what are they here 900 by 500 that seems like a reasonable size to make our spaceship but feel free to make this larger feel free to make it smaller feel free to make it square mess around with it and see what you get but anyways that's going to scale our spaceship now so it'll be much smaller so let's do the same thing for the red spaceship so let's say red underscore spaceship like that is equal to pygame.transform.scale and then red spaceship image we're going to resize to the same thing 55 by 40. now since i'm using these numbers multiple times and i might use them later on make sense just throw them in a variable so i'm just going to say um you know space ship underscore width and then spaceship like that underscore height is equal to and then 55 by 40. and now i'll just replace these values just in case we ever want to change this it will work everywhere in the program so spaceship width and then spaceship height like that let's copy this and let's simply put it here okay so now that we have that before we rotate it let me actually just update this so instead of drawing a yellow spaceship image i'm just drawing yellow spaceship because yellow spaceship i know it's kind of messy to see here is now the one that is scaled down so let's go ahead and run this and see what we get and now we get a much smaller spaceship that looks much better to me maybe it needs to be a bit taller but honestly totally fine so let's leave it at that okay so now we need to rotate this image so to rotate it i'm actually going to go and find yellow spaceship and in fact let's separate these to make it easier to see and i'm going to wrap this scale within a a rotate so you'll see how it works but let's go pygame dot image dot rotate oops like that okay and now i know it's confusing with the brackets i'll go through it we're going to pick the angle that we want to rotate this at so i'm pretty much saying pigment.image.rotate this is the ending bracket at the very end there we're plugging in this as the thing that we want to rotate which is the scaled down yellow spaceship and we pick how much we want to rotate it so rotate it i want it to rotate to the right and i want to rotate it 90 degrees now let's see if that's correct we might have to rotate it 270. i forgot which way it was facing originally but let's see if this actually gives us the rotation so let's run uh and there's no pie game oops sorry guys uh this is not pygame.image.rotate i just got an error there this is pygame.transform.rotate so i make that fixed there on line 15. okay so run now and there we go we can see it's facing the correct direction okay so we've done that successfully now with the yellow spaceship now we want to take the red spaceship and rotate it but so it's facing the other way so let's copy game.transform.rotate let's wrap this here again and then let's go comma and let's rotate this one 270 degrees because we want it to face the other way so now we can draw the red spaceship as well so let's go down here and let's say wind.lit oops didn't mean to open that wind.blitz let's split the red spaceship and let's put a little bit further away let's put out 100 100 or actually let's put at 700 100. okay so take a quick look at this make sure your code matches now let's run and there we go we have our two spaceships facing each other all is looking good okay so now we have the spaceships now i want to show us how we can move these spaceships around so to move these spaceships is not actually super complicated but we need a way to keep track of their x and y position i guess as well as their width and height and then to change that position and pretty much just change where we're drawing them to be at their x and y position so what i'm going to do now is i'm going to write a little bit of code i'm going to go a bit faster than i've been going and then of course we'll stop and go over everything to make sure that you guys understand let's go down into our main function and now what i want to do is i want to define two rectangles which are going to represent my yellow spaceship and my red spaceship so i can control where they're moving to so just follow along and then we'll explain what it is so red equals and i'm going to say red this is going to represent our red player is equal to pi game dot rect like that and inside of here what i'm going to do is simply define the position or a rectangle that represents this red spaceship now you'll see why we're doing this but the pos or the arguments sorry for the rectangle are x y width and height so i define the x position the y position and the width and the height that i want my red player to be at so we already know what the width and the height are going to be because that's going to be equal to whatever we scaled our spaceship to right which was spaceship width and spaceship height good thing we stored that in a variable but the x and y we can pick now we want the red spaceship i mean we can decide this but let's say we'll put on the left-hand side of the screen so in that case let's make its x and y something like this so we'll make its x position 100 and let's make its y position 300 and then for its width and height we already know what this should be spaceship width and spaceship height okay so now we're gonna do the exact same thing for the yellow player here so let's instead of red let's change this yellow and then let's just change its x position so it's over near 700 so they're far away all right so now we have red and we have a yellow rectangle all i'm going to do now is i'm going to pass this rectangle so actually both of these rectangles red and yellow over to my draw window function so now inside of draw window i'm simply going to take red and i'm going to take yellow and rather than drawing my yellow spaceship in my red spaceship at a kind of predefined position i'm going to draw it at whatever position my red and yellow argument are at this way i can modify red and yellow and when i pass it to draw window it will change where we're drawing these rectangles so uh let's or these spaceships sorry rectangles just because we're representing them with rectangles but for our yellow spaceship we're going to draw this at yellow.x and yellow.y now the reason we have access to dot x and dot y is because yellow is a pi game rectangle and it defines that the x is this and the y is this so it just makes it really nice for us to use so yellow.x yellow.y now for red we're going to say red.x and red dot y like that so now we draw a red in our yellow spaceship now to show you how this would actually move around let's just do something really simple every single loop i'm going to move my yellow spaceship one pixel just so you guys can see it moving on the screen so i'm going to say yellow dot x plus equals one all this is going to do is add one to the yellow x position and move it in fact let's actually change this to red because red will have more time to move so this will move 60 pixels per second because the clock is ticking at 60fps and we're updating the x position 60 times and adding one to it so hopefully that's clear but let's run this and now notice that we have a red spaceship moving in uh the incorrect direction on the screen and i noticed that i actually put these spaceships on the wrong side because of the way that they're facing so we have two options we can change where they are so we can just change 700 100 or we can change their rotation i think it's easier to just change this right here so let's change 700 100 so they are on the right side of the screen let's run this and now you can see it's moving backwards but they are on the correct side of the screen now the reason this is moving again is because we're updating the exposition and we're drawing it at the x position so as we change red here well we're passing that updated red over here and then it's it it's moving right so hopefully that's clear but anyways that is how we would move it so now what we need to do is we need to actually change the x and y position when we press the arrow keys right so that we're moved based on the user input so we have two things that we need to check we need to check whether the red spaceship is moving or whether the yellow spaceship is moving now let me just run this one more time yellow spaceship is on our left red is on our right so we want to use wasd for the left and the arrow keys for the right spaceship because that just intuitively makes sense on the keyboard so let's start doing this i'm going to start doing it for the wasd keys so for the spaceship on the left which i can never remember i think it's the yellow one yeah it is the yellow one and then i will show you how we can do it for the red and how we can kind of clean up the code a bit so there is multiple ways to do this in pi game you may have seen if you've watched other pie game tutorials of mine that i don't use the method i'm going to use here the reason i'm going to show you this method is because this allows you to press multiple keys at the same time whereas the other method i've shown previously which i'm just not even going to bother showing here only lets you press one key at a time actually we'll show it later in the video so i can talk about it then but anyways what we're going to do is say keys underscore pressed is equal to pi game dot keys actually sorry just dot key dot get underscore pressed what this is gonna do is every single time this while loop is running and we reach this line so 60 times a second it's going to tell us what keys are currently being pressed down this way we can just look at all of the keys check if the ones that we're looking for are pressed down and if they are respond to that press this also means that if the key stays pressed down it will still register that it's being pressed so it's super useful and well you'll see as we get into this how this works but all we have to do is say if keys underscore pressed then inside of here pygame dot k underscore and then the name of the key that we're checking for you can kind of see a list is popping up on my screen here on how they work the ones that are special keys are in all capitals and the ones that are just letters or numbers are usually just lowercase although i guess you can't really capitalize a a number but anyways we're going to start by checking up down no we'll go left right up down so the first key is going to be a so this would be left right so let's just leave a little comment here let's say this is left so if we press the left key what should we do well we should move the spaceship to the left how do we do that well if we looked at the top left being 0 0 that means if we're going to the left we're moving closer to 0 0 on the x axis so let's subtract from our x value to move us backwards or to move us to the left right so closer to 0 0. so this since this is for the yellow spaceship we're going to say yellow.x minus equals and then what should we minus here well how much we want them to move when they press down this key now since we're going to use this multiple times it makes sense to go to the top of our program right after fps we can say velocity or vel is equal to and then i'm just going to set this equal to 5 feel free to change that around and make that whatever you want but let's make that five and now let's say yellow dot x minus equals velocity now before we go any further and get into more keys let's test this and see if this is working so keys pressed equal pi game dot key dot get underscore pressed gives us a list of all the keys we check with this expression right here if the a key is being pressed if it is we modify the x so subtract values from it which will move us to the left so let's try this i'm going to press the a key and notice that i can move left obviously i can't go anywhere else there you go and now i'm off the screen so that's something we're going to have to check as well if we're off the screen we're not going to have to let someone or we're going to have to disallow someone from moving or off the screen but for now that's fine we'll do that after so now let's handle the other keys so we can actually copy this line right here let's fix the indentation now instead of the a key let's do the right key which is going to be d so let's change this comment to right i actually just want one space for my comment here now yellow.x since we're moving right rather than subtracting the x we want to add to the x so let's add to it like that and now let's try both these keys so now i can move left and right but i cannot go up and down and keep in mind i can go off the screen in either direction so again something that we're gonna have to check okay so we've done that now now let's do the up and down key so we can copy this again and this modification will be pretty easy so now for up that's going to be w for down that's going to be s so let's change this comment to be up let's change this comment to be down and now instead of the y being modif or sorry so the x being modified i kind of spoiled it the y is going to be modified so that's actually all we have to do but what this is doing now if we're moving up we need to subtract from the y because the top left is 0 0. so when we go down that's adding to the y so when we go down with s we add to the y value and that will move us down so let's save that let's check this i'm going to run and now i can move up down left and right and kind of on diagonals because i can press the same keys at once right so if i press down and left or i press up and right you can see that i'm moving diagonally so that's great now what i want to do is actually take this and i want to put this in a separate function because it's going to get kind of messy if i'm doing this twice inside of this loop right here right so i'm just going to copy all this code that i just wrote i'm going to write a function here i'm going to say define yellow underscore movement like that now actually we could say yellow handle movement or something that makes more sense yeah yellow handle movement inside of here is going to take an argument called keys and all i'm going to do is the exact same thing that i have before and actually this argument is going to be called keys underscore pressed and i'm also going to take in yellow now it may seem that this is over complicating things but trust me it's going to be nicer when we do the other movement for the other character we're taking in that keys press list we're also going to take in the yellow character our code doesn't change whatsoever we've just moved it so that it's kind of separated and it's easier to see so now what i'm going to do inside of this loop is i'm going to call yellow underscore handle movement like that really i probably should have called it handle yellow movement but that's fine we're going to pass keys underscore pressed and then we're going to pass yellow like that now what this will do is it will give the keys press list that we need and it will give our yellow character and then we'll just do everything we were doing before but inside of this function now you can probably guess how we're actually going to handle the right players or what am i saying the right players the red player all we need to do is copy this function we'll just do a paste like that and now we're going to do the exact same thing except instead of yellow it's going to be red instead of a dws it's going to be up down left right or i guess left right up down so let's change this to red let's change the name of this function to red as well and then we can just change all of these yellows uh to be red i'm just going to do them manually but if you're fancy you could use the find and replace all right so exact same thing now we're going to change our left right up and down the arrow keys are really easy it's literally just k underscore left okay underscore right oops okay underscore down and k underscore oops well i did in the wrong order okay underscore down k underscore up all right so that should be good we don't need to change anything else now all we need to do is call this so let's call this function red underscore if we could do it in the right case red underscore handle movement let's pass it the same thing keys underscore press like that and then red now the red movement will be handled let's make sure this is all working so let's run this and you can see that i can move my left guy and now i can move my right guy and they move at the same time with no issues awesome so that is great we're making good progress but now we can move off the screen right so we need to handle this so that we can know because we can no longer move off of the screen but before we do that just because it's going to make this part easier and less repetitive let's handle the fact that in the middle of our screen we want a border right so i don't really want my red and yellow spaceship because you remember the game we made at the beginning to kind of be able to face like right beside each other i want them to have their own halves of the screen and not be able to cross over so let's make a rectangle that's kind of a border and divides the middle and then we'll draw that on the screen and make it so that our characters can't move past that border so let's go to the top of the program and we're just going to define uh wherever we want doesn't matter i'm going to say border in all capitals and this is going to be equal to pi game you guessed it dot rect this is just going to be a rectangle and we'll just draw this rectangle onto the screen so i need to pick where this is going to be so let's be clever about this where should my rectangle be i need the x and y position and then the width and the height well the x position we'll need to figure out the y position is obviously going to be at 0 because we want to start at the top of the screen and go all the way down so we're going to say y is equal to 0 the width and the height so the width we can kind of pick what we want the width to be i'm just going to make it 10. the height needs to be the height of the screen because we're starting at zero so it needs to fill the entire screen and then the x is what we need to figure out so i want this to be exactly in the middle of the screen which means i can say width over two that's going to give me 450 right to be in the middle but then since we have a width of 10 let's just go to paint here quickly i'll show you what happens if we do that so let's say we have our screen you know this is width over 2 and this is like right in the middle of the screen okay so this is me trying to do a 5 with my mouse this is 450 okay now if i draw a rectangle here that has a width of 10 what's going to happen is i know this is like a really exaggerated width but we're going to draw it like this right i don't want to draw it like that i want to draw it like this so how do i do that well i need to subtract half of the width so i can figure out where the 0 0 position of my rectangle should be because really i'm not drawing the rectangle from the middle i'm drawing it from 0 0 so i need to draw it such that it will be in the middle of the screen when i draw it if that makes sense so anyways the point of this is saying that if we have a width of 10 i need to subtract 5 from its x position so put it at 445 so that way it draws in the middle so let's do that rather than i guess since our width is hard coded i'll just subtract 5. and now once we draw this on the screen you'll see that it is right smack in the middle so let's draw this let's go here and let's say win dot blitz no it's not going to be actually okay you guys are going to be confused with this but we're going to draw this another way so we're going to say pi game dot draw dot rect so we're taking a rectangle and what i'm going to do is i'm going to say we're drawing this on the window so the arguments for this specific pi game function is the window or the surface that you're drawing this onto in this case just our main window then we need to pass a color that this rectangle is going to be so i actually want this to be black so what i'm going to do is define another color here i'm going to say black is equal to 0 0 0 because well that's the color code for black it's just none of red green or blue so anyways we define black so now we're saying we're drawing on the window it's color black what are we drawing well we're drawing a rectangle so i just pass in my rectangle which is border like that because border is equal to a pi game rectangle so that's all we have to do so let's go ahead and try this i'm going to press run and now we get a nice black border right perfectly in the center of the screen now of course i can still go over it and notice that we're drawing actually below the border um are we on top of it no we're on top of the board okay that's fine it doesn't really matter if we're on top of the border or not but now we need to make it so we can't actually cross this border so really all we have to do to make it so we can't go off the screen is not let our player move if they're gonna move off of the screen so we just check if pressing this key would move them off the screen and if it will then we'll just not let them press it so inside of my yellow and red handle movement it's kind of annoying i should have done this before so we could just copy it in we're just going to make sure that we're we can't move off the screen or into the border so for yellow on the left hand side of the screen yes on the left-hand side of the screen what we're going to say is and just in this if statement right here and we're going to check if by moving to the left we would have a position that is in the negatives so that is not equal to at least 0. that would tell us that we're off the screen because the 0 0 of our image would be well not on the screen so i'm just going to say and yellow oops did i mean to press that yellow dot x minus velocity is greater than zero so what this will tell us is if when subtracting the velocity from our current y position that will be greater than zero or not if it is we won't let ourselves move any further to the left so the reason i'm doing minus is because we're obviously gonna subtract to move to the left now we'll do the exact same well actually we're gonna do a different thing for the right we're gonna say and yellow and yellow.x plus velocity the reason it's plus is because now we're moving to the right now in this case we don't want to check if it's greater than something we want to check if it's less than something now what do i want to check if it's less than well i want to check if it's less than the border in the middle of the screen because if we look at the screen right this is on the left hand side we don't want to be able to move past that border which is in the middle of the screen so we'll get the borders x position and we'll put that here so we'll say border dot x so this will not let us move past the borders x position but the issue with this is you have to remember that we're drawing the image from the top left so technically the width of the image can still move over the border because the 0 zero position wouldn't be past that x now hopefully that makes sense but to show this to you again we go back to trusty paint we have our border in the middle of the screen let's say this is our rocket ship like this technically this zero zero is less than this borders x but its width is over top of it so what we need to do is check the width of the the image as well and make sure that the zero zero plus the width of the image isn't going to be over top of that border so a lot of explaining here but all we have to do for that is simply say yellow dot x plus vel plus yellow dot width like that and again this is another property of the rect we can call a dot width and that will make sure that we are not over the border okay now we'll do the same thing for up and down so for up it's really easy we're going to say yellow dot y minus the velocity is greater than zero and we'll do the exact same thing here except instead of the width and the x's we're just going to check the heights so we're going to say yellow dot y yeah plus velocity plus yellow not dot width but dot height is less than and actually in this case it's not going to be border.y this is simply going to be height because it gives us the height of the screen so this is making sure that the height and our image cannot move further down past the screen now let's just test this then i'll do the same thing with red so run and now notice that i can't move any further down the screen okay i can't move left off the screen i can't move right off the screen and in fact this is blocking quite a bit and same thing here now there's a slight problem going down i'm not sure exactly what that is all right so i just pause for a second because for some reason my yellow guy can move further down the screen i'm not actually really sure why that is so a simple fix for this i don't usually recommend this but since it's not that important based on the game we're making i'm just going to add a few pixels to this right here so i'm pretty much going to say and yellow.y plus velocity plus yellow dot height is less than and then height minus five now what this should do ideally is just make it so that we can't move as far down so let's just rerun this and actually sorry it's already running so let's close that and run again okay now we can move okay so five clearly wasn't enough we can't move as far down now but let's just make this ten so let's go height minus ten now let's run the game and same thing okay so let's make this a bit more let's make this 15 pixels let's run let's see it and there we go now we're like perfectly at the bottom of the screen okay so that's what i wanted now you might be wondering why on the other edges we're not like touching them immediately that's because the actual size of this image is a bit bigger than what's showing up on the screen um that's sometimes a problem like if you take an image and it's like really small compared to the actual dimensions of the image then the rectangle around that image is going to be bigger than what the actual image is so that's pretty much why we can't cross this border here because this image actually kind of extends further out you just can't see it because it's a transparent background anyways hopefully that makes sense let's do the same thing for red now and then let's get into firing bullets and some more fun stuff okay so close that oh i launched this game like 12 times okay great okay close it all right so now we're just going to copy this and do the same thing for red so instead of yellow just change this to red we can literally copy everything and just change all the yellows to rent so and red oops not like that and red.x and red copy this one here this one will be red and same for this okay and red and red all right so now we have that let's just test this last time make sure all is good come on run what's happening invalid syntax where did i make a mistake let's see it is saying i can't even see because my window's not big enough at red dot x ah i forgot the and sign on all of these great let's add the and sign back or the and word i guess okay run now and there we go there so now yellow is good red's good ah but red c so red can move crop across the border now the reason red can move across the border is because i forgot that we need to limit how far it can move to the left not to the right so let's go to red and actually we do need to change some of these things so for moving to the left rather than checking if it's greater than 0 we want to check if it's greater than the border dot x plus the border dot width okay so we're going to have that there then if we're moving right this isn't going to be reliant on the border this is going to be reliant on the edge of the screen which is simply going to be the width of the screen so hopefully that's clear why we're doing this but now we're making sure that we can't move further left than the border and going to the right this is different than yellow obviously we can move as far right as we want so long as we don't go off the screen so let's run this now and let's try red and there we go we can't move to the back of the screen and the border yeah we can't move past the border either down is good up is good awesome we are looking good all right so now what i want to do since we've just finished that is i actually want to start talking about bullets so how we can uh actually have projectiles firing around the screen now this is a little bit more difficult than what we just did but of course it's important to cover in this tutorial so to handle bullets what we need to do now is have a separate key that each character each person can press that will fire a bullet or a projectile from their character so to do this we need to maintain a list of all of the bullets so the first thing i'm going to say is bullets is equal to an empty list like that we also need to decide how fast we want these bullets to go so i'm going to make a variable here i'm going to call this bullet underscore velocity and we can either decide to make this slower than the characters or faster than the characters but since i want this to be faster and make it a bit harder we're going to make it 7. again feel free to play with these numbers so we're gonna say bullet val equals seven so now what we need to do is make a way for us to actually create a bullet and have it kind of fired around the screen so i'm gonna show you now how we can handle the presses of the left and right control so usually i would use something like the space key to fire a bullet but since we have multiple people playing on the same keyboard we can't use space because only one person can press that so i think it makes sense to use the left control and the right control to press to fire the bullets this way you don't get sticky keys when you're pressing the shift key which is what i would have done previously and obviously we don't want to use enter and caps lock because what caps lock is not an intuitive key to fire a bullet so we'll go with right and left control now we're going to do that but the thing is i want each player to have a limited number of bullets so i don't want them to just spam bullets as many as they want or fire them like rapid fire on the screen so that also means that i don't want players to be able to hold down the key to shoot bullets i want them to have to press the key each time so they have like a very methodical shot right not like saying call of duty or just holding down the trigger the entire time i want them to have to actually press it each time so let's do that the way we're going to do that is by not handling the key presses this way we're going to handle it this other method there's not really names for them so it's hard for me to describe them that i talked about at the beginning of the video so what we're going to do is say if event dot type equals equals dot key down like that now this is telling us hey we pressed a key downwards then what we're gonna do is fire a bullet so we need to check whether we press the left control or the right control so if event and then oops like that dot key is equal to pi game dot and then this is going to be k underscore left i think it's l c t r l yeah l c t r l is left control and then otherwise we'll say if event dot key is equal to pygame.k underscore r ctrl standing for right control then we will kind of create a bullet for our character so the idea here is i want to have a list of bullets this list is going to store all of the red players bullets and all of the yellows players bullets or in fact to make this easier let's actually just do two lists let's say red underscore bullets equals that and let's say yellow underscore bullets equals that so what we'll do is we'll have the red bullets list or all the red players bullets yellows will store all of the yellow players bullets and then we'll move these bullets around the screen and kind of add them to the list so to create a bullet we'll just add one to the list and then we'll draw these bullets at their x and y position and we'll automatically move them so that they're going kind of in the direction that they were fired so the first thing is to create the bullet obviously so to do this uh for left control we want our bullet to be going to the right so let's do that so we're going to say uh i guess who is on the left i always forget i think it's yellow yeah yellow is on the left we're going to say yellow underscore square bullets dot append and just to make this easier to read i'm going to say bullet and the bullet is just going to be equal to a pi game rectangle i don't have any fancy images for this one so we're just going to say pygame.rect like that we're just going to create a rectangle that is at the position that we want to fire it from so if we think about this where should we place the bullet well the bullets really should be placed at wherever the yellow character is right we want the bullet to come from their body so since the yellow character is facing to the right the bullet should kind of spawn or appear at the edge of their body so at their x position plus their width that way immediately when you press the fire button you you see the bullet kind of coming out of the character so to do this we're going to say that the x position of our bullet and we're just going to make it a rectangle again is going to be at yellow.x plus yellow.width like that now if we think that this is too far away from the character because remember the width of the image is a little bit further than the actual character itself we could subtract a few pixels and it would be like more inside it doesn't really matter but anyways let's say bullet equals pi game.rect yellow.x plus yellow.width now for the height we can say this is going to be yellow dot y now it's going to be weird but we're going to say yellow dot height over 2. so we're taking the yellow dot y position which is the top left-hand corner of the image and then we're adding the height of it over 2. the reason for this is so that it comes directly in the middle of the character because if we did it from yellow.y it would come from the top left of the character which we don't want we want this to come from the middle of the image so we simply add half of the height to put it in the image to put it in the middle and really if we want to be even more precise we should then subtract or we should then add depending on what actually it's going to be subtract in this situation half of the height of the bullet so the height of the bullet i think is going to be 5 pixels so i'm just going to subtract 2 because i don't want this to be a decimal number but anyways you guys will see i apologize this is a lot to take in at once but i just want to make sure this is perfect so yellow.x plus yellow.width to put that in the middle x position or sorry to put that on the edge of the image then yellow.y plus yellow.height over 2 minus 2. this is so the bullet comes directly from the middle of the character then the width of the bolt is going to be 10 pixels and the height is going to be 5. so that is our bullet and then all we're going to do is append this into the yellow bullets list perfect so let's copy this and let's do the exact same thing except for red for our right control button press so now instead of having yellow.x this is just going to be red and we'll literally copy the same thing except we need to remove this plus red dot width the reason for this is the red character is facing to i guess the left of the screen i know my hand positions are probably wrong but it's facing to the left so its bullets are going to move towards 0 0 which means we want the bullet to come out of actually the left side of the character not the right side of the character i would run this but there'll be a crash right now if i do that so let's actually um i'm just going to try to go through this the character is facing to the left so we want to start drawing the bullet at its actual left edge which really is it's just x position so instead of adding the width to it like we did with yellow we're just going to put red dot x now the height will be the same thing because we do want it to be in the middle for the height so red dot y and then red dot height and then literally everything else is the exact same it's just the edge in which this bold is appearing we want to be different okay perfect now last thing and there's actually more before i can show you these bullets firing we want to make sure that each player has a finite number of bullets so to do this we need to define another variable and we're just going to call this num underscore bullets like that or actually to make it more clear we'll say max underscore bullets and we'll set this equal to whatever we want i like three you guys can change that but i like three bullets so now before we actually go ahead and check if we can do the left control or we can do the right control we want to make sure that we don't already have three bullets fired on the screen because if we do we need to wait until those bullets disappear go off the screen whatever before we can fire another one so i'm going to say and the len of right what am i saying right red no this is yellow yellow underscore bullets is less than max underscore bullets so if the amount of yellow bullets that we have which is defined by the length or the number of bullets in this list is less than our maximum bullets we can go ahead and fire another one otherwise no don't add another bullet to the list because we already have the maximum on the screen now same thing here and the len of red underscore bullets is less than max bullets perfect now this will allow us to actually fire bullets on the screen now because it's going to take a second before we actually see these i'm just going to print out red underscore bullets and then yellow underscore bullets so this way when i start pressing the right and left control key in my console down here where all this gibberish is appearing you will see it popping up the bullets list so let's do this you can see that it's empty now when i press ctrl boom there you go we have a a button or a uh bullet inside of the list i press control again i press the other control and you can see that there we go going ahead and adding to the list now i realized as i did that in good job we did that here instead of having yellow bullets this needs to be redbullets dot append because obviously that well that just wasn't working with yellow it was adding all of them to the yellow list which we didn't want so hopefully that's clear but that's how we have the bullets now they're in the list when i press left and right control boom they're getting added and well it will work the maximum it just wasn't working before because we had a bug this was yellow instead of red okay perfect now we have that now we need to move the bullets and we need to see if they hit any of the characters so what i'm going to do is make another function that can handle this for us because it makes sense to kind of separate everything out so what i'm going to do is i'm going to make another function down here i'm just going to start typing it out then i'll define it above and i'm going to say this one is handle bullets like that now we're going to pass the yellow bullets the red bullets and the yellow character oops or the yellow rect as well as the red uh yeah i guess as red as well the reason for this being that we want to check if any of these bullets collide with either of the characters because if we do well we'll need to do something about that right and same thing we need all the bullets so that we can handle moving them around the screen and drawing them and all that all right so now let's code out this handle bullets function so let's go here it doesn't really matter where we put it and let's say define handle underscore bullets let's have this take the yellow bullets the red bullets the yellow character and the red character okay so what this function is going to do is move the bullets handle the collision of the bullets and handle removing bullets when they get off of the screen or collide with a character so what we'll do is we'll loop through all the yellow bullets check if they've collided with the end of the screen or with the red character then we'll loop through all the red bullets and do the same thing except for the other character so let's do this i'm going to say four bullets in yellow underscore bullets like that then i'm going to start by moving the bullet so since it's a yellow bullet it's coming from the left which means we need to move it to the right because it's coming from the character on the left so we're going to say bullet dot x plus equals the bullet velocity to move it to the right so we move it and then after we move it we're going to check for collisions we're going to say if yellow now there's this fancy thing in python or in python in pi game called collide rect and we can pretty much check if the rectangle representing our yellow character has collided with the rectangle representing our bullet this is pretty easy all we do is just pass bullet right here and what this does is tell us that hey yellow did collide with the boulder both did collide with our yellow rectangle or it didn't so this is true or false but this is really easy way to check for collision use collide rect keep in mind this only works if both objects are rectangles which they are and that's why i used the rectangles okay so now that we have that we're going to do something kind of fancy if we collide with the yellow character the first thing we need to do is remove this bullet so we can just say yellow underscore bullet dot remove and we can remove the bullet that's fine we're going to delete the bullet because it's gone it collided but we need to tell our main game loop down here somehow that we collided with the red character right we need something to pop up we need to remove health whatever it is we need to do something but i can't directly modify anything in my main game loop from this function right other than the stuff that was passed to it so what i'm going to do is i'm going to post an event now in pi game there's these things called events right just like event dot quit just like event dot key down right whatever uh you're we're checking the types equal to pi game dot key down pi game dot quit so i'm going to post an event create a new event and then we can check for that event inside of here and do something if that event occurs now this event is going to be red collided or you know bullet hit red or red hit or whatever we want to call it we'll do the same thing for yellow we're going to post an event that we will then check for in this while loop so to do this we need to first create this event so i'm actually going to go up to the top of my program here we'll do like kind of a new section i'm going to say in all capitals yellow underscore hit and then we'll say red underscore hit like that and this is going to be equal to something that's kind of weird but pi game dot user event plus one and for this one pygame dot user event plus two this just represents the code or the number for a custom user event since we're going to have multiple user events we can add one to this one and add two to this one so now we have two separate user events that we can check for and handle i know this is strange but this is how you create a new event you say pi game.uservent plus some number obviously going up in sequence so plus one plus two plus three plus four if these were both plus one they would be the same event because they would have the same underlying number representing them this right here uh to my understanding is really just a number like it's you know 450 it's some number we don't know what it is we just add one to it to make sure we have a unique event id that's pretty much what we're doing so yellow hit and red hit those are my two events so we're going to go down here uh we're going to go into here sorry and up here we're going to say pi game like this dot event dot post and we're going to post a pie game dot event i think it's dot event dot event like that and inside of here we're going to pass the event that we want now actually sorry this should have been red not yellow so red dot collide wrecked because we're checking if the yellow bullet's hitting the red character so you guys probably saw that that should be red and the event we're going to pass is or post is red underscore hit so this is telling us or we're making a new event that's saying that the red player was hit now we'll literally copy all of this and do the exact same thing for not our yellow bullets but for our red bullets so we'll say red like that we'll change red to yellow and then instead of yellow bullets this is going to be red bullets instead of red hit this is going to be yellow hit now this is the exact same thing except now we're checking the red bullets but we need to move the red bullets in the other direction because we're firing from the right of the screen moving to the left closer to zero zero so we subtract the bullet velocity so this handles our yellow bullets this handles our red bullets and that should be it for moving the bullets so let's actually try this out and let's see how many mistakes that i've made assuming we made any so refresh we have our two uh ships now i'm going to press ctrl and ah we got an issue deprecation integer is required but got type float i'll be right back just gonna have a look at what the issue is here alright so i found the error pretty silly one i should have came up with this pretty much we cannot have floating points when we create a new pi game rectangle so for both of our bullets we need to actually put two slashes here for integer division it's fine this is gonna round anyways it'll be okay we just need to do integer division so red dot height integer divided by two yellow dot height integer divided by two uh so that way we don't get any floating point issues now same thing here with this border it's going to go to our border and we have width over two we're going to change this to over over two so that way again we don't have that floating point issue that we're running into before but this was indeed working uh with despite of those two issues so just fix those division signs to be two division signs so slash slash but i realize that we're not drawing any of these bullets so let's draw these bullets onto the screen because it's going to be hard for me to show you that it's working without drawing them so inside of our draw window now i want to take actually just let's just take a list of bullets so what we'll do is we'll combine the you know what i can't do that because it's going to be drawing the wrong color let's take red underscore bullets and let's take yellow underscore bullets doesn't matter what order we take them in and let's draw these bullets onto the screen so after i draw everything else we'll draw our bullets so we're going to say four bullets in red underscore bullets then what we'll do is we'll say pi game dot draw dot rectangle we'll draw these onto the window these are going to be red so this is an opportunity to create another color called red so let's go here we're going to say red is equal to 255 0 0 because red well is all red and nothing else we also need yellow so let's go ahead and do that now can i remember my primary colors i'm just going to look so i don't mess this up i mean i believe this is red and green creates yellow i think that's correct so let's go here with yellow so 255 255 0. okay and now we have red and yellow so we can draw pygame.draw.rect window color red and what are we drawing well we're going to draw the bullet which is really just a rectangle copy this do the same thing and the only thing that we need to change is the color so this is going to be yellow and this is going to be yellow there we go so we have our two colors defined we're now going to draw the red bullets and all the yellow bullets on the screen so we just loop through them and just draw all of them out okay so let's refresh or let's run this and draw a window missing two required positional arguments red bullet and yellow bullets that would make sense because i forgot to pass them so let's go down to our main function here see where we have draw window we're going to pass the red bullets so lowercase red bullets and lowercase yellow bullets awesome quickly just so you guys can see everything i'm going to zoom out i give you an idea this is what the main function looks like in case you guys are on a larger display and you want to see all of it this is what the other functions look like just going to kind of scroll through so you guys can have a look here and pause the video if you need a specific part or if i'm going too fast for you okay so let's zoom back in let's run and let's see if this is working now so i'm here on my left guy i press ctrl boom we fire a yellow bullet kind of hard to see on the white background but also notice let's let's go with the right one because you're able to see the red that this bullet when it hits my player it's disappearing that's awesome this is working and boom we're good to go so now what we need to do and also notice if you try to hit control a bunch of times it only lets you shoot at most three bullets at a time right which is exactly what we wanted if i go up here now i can't shoot any bullets until these go off the screen and in fact i forgot to handle the fact that the bullets go off the screen we need to remove them so let's do that next awesome so much stuff i always forget how much stuff we actually need to do so now after we check this collide rectangle we're going to check if any of these bullets are off the screen so to do this with the yellow bullet all we have to say is if bullet dot x and this one is going to the right is greater than uh and we're not going to bother with the width or the bullet or anything it's fine it will just make it disappear when it gets to the edge we'll say bullet dot x is greater than the width of the screen than yellow bullets dot remove bullet but we'll just do an else here to make sure that we don't so this will be l if so that we don't potentially remove the bullet twice anyway so we'll do that now we'll add an lap here we'll say l if bullet dot x is less than zero because that would be when it's off the screen if we're subtracting the velocity then same thing here red bullets dot remove and bullet so that should be good just checking if it's going off the screen in either direction okay so let's try this now when i press control a bunch of times boom i should be able to press it again awesome they're getting removed all is good all right so before we do anything else let's actually just change the background because my eyes are hurting with that yellow on white so we'll change it to that nice space background that i showed you at the beginning so to do this we need to load in our space background if we go to our assets folder we can see we have space.png so we're just going to say space is equal to pygame dot image dot load and then we're going to load in dot path dot join so os dot path dot join with the assets folder like that and then we want to load in space dot png now that is that's fine we can do that but i'm also going to rescale this image because it's really big to be a lot smaller just so it looks nicer so to do that we'll say pygame dot transform dot scale and then we'll wrap this image around and inside of this we'll put the dimensions now we have perfect dimensions for this we can just make it the width and the height of our window now this might make it a little bit kind of stretched we'll have a look at how it how it looks but i'm just going to make this width height so we're resizing it to that so now rather than filling the screen with white every single iteration and actually let me show you what happens when i don't do that because that's interesting so before i draw the background i'll show you what happens when we don't fill the screen with white look you can see this i'm just moving around all over the place the reason this is happening is because pie game does not remove the last drawing that we made right it just keeps drawing stuff onto the canvas so if i don't draw a white background every single frame i don't draw something that covers the entire screen then you get all this kind of movement stuff because it's not erasing anything that it previously drew so anyways i just thought that was interesting so let's now put that image onto the screen i'm going to say win in all capitals dot blit we're going to blit space and then we're going to put it at 0 0 because this is the background so we can just start at the top left and fill the entire screen because we already know its width and height is that so let's go ahead and run and there we go we get a nice space background actually doesn't look bad at all in fact this looks pretty nice so i'm going to leave it like that awesome then we can go there you go yellow looks a lot nicer on that background awesome so now let's handle those events so when we actually get hit we need to do something we need to have some health or something like that then we're going to add sound effects we've got a bunch of stuff well actually not that much but a few more things to do so now inside of my main event loop remember just a quick refresher we're posting these events right yellow hit and red hit so when we post these events they just get added to this pie game.event.getq that's kind of appearing with all of the events so all we have to do is just inside this for loop check for these events so if event.type equals equals red underscore hit then we'll do something and if event dot type equals equals yellow underscore hit like that then we'll do something else so this is a perfect time to implement a notion of health so we want to have both characters have some number of health and every time they get hit that's obviously going to subtract so to do that pretty straightforward but we're going to make two variables here we're going to say red underscore health is equal to 10 and yellow underscore health is also equal to 10. whenever a player has zero health again feel free to change these numbers then we'll say that the opposite player has one so that'll be kind of the objective or how you win or lose our game so if red is hit what's the obvious thing to do subtract red's health so red health minus equal one if yellow is hit then we'll say yellow underscore health minus equals one then what we want to do is now check actually we don't need to do it inside of this for loop but we can do it outside of this wall if either player has health that is equal to zero and if they do the opposite player will win the way i'm going to do this is interesting but i'm going to say if let's say if red underscore health is less than or equal to zero and then i'll say if yellow underscore health is less than or equal to zero i'm actually going to define this variable i'm going to say winner underscore text equals and i'm going to say yellow wins like that now on the other side i'm going to say winner underscore text is equal to red wins this is the text that i want to appear on the screen when either of these situations happen we'll get into this in a second but i just want to start defining it now above here i'm going to say winner underscore text equals a blank string and i'm going to check in one more if statement if when our underscore text does not equal blank then inside here someone won so the basic logic behind this we have this variable called winner text it's equal to nothing if either the red player or the yellow player has lost so they have zero health then we will set the winner text to be something other than empty string in the situation where winner text after we check both of this is not equal to an empty string someone won we should display that winner so we will get to that in a second but now what we want to do is show both of these scores on the screen and then once we've done that we just have to add sound effects handle someone winning and we're pretty much done we're getting very close so let's do this let's start showing the score to show the score that means i need to pass the score to my draw window and i need to somehow draw that score in the window so i'm just going to pass the i guess it makes sense to pass red first so we'll pass red health and yellow health like that to my draw window now let's go to draw window let's now take inside of draw window the red underscore health and the yellow underscore health like that and now inside of here what we'll do is we'll actually draw these their score or their health on the screen now to do this this involves using fonts we have to actually render some text on the screen so this is where we get into our next step so what we're going to do at the very top of our program is we're going to say pygame dot font.net now i just took a quick pause there because as you guys can see i spilt water on myself so that's great but we'll continue that's fine i will survive anyways you're going to put pygame.font.init at the top of your program and this is going to initialize the pi game font library or whatever it may be then what we need to do is define a font that we are going to use so it's getting kind of messy up here i'm just going to do another kind of little section and i'm going to say that the health underscore font is going to be equal to pygame dot font dot sys font with these specific capitals we're going to define the name of the font which i'm just going to use comic sans and then the size in this case i'm going to pick 40. so what i'm doing here is i'm just defining the font that i want to use comic sans size 40. we're all good we can continue alright so now that we have the font defined we need to use it so we're going to go inside of draw window i'm going to show you how we can actually put font onto the screen uh now draw this wherever you want just obviously after the background's drawn i'm just going to draw it after the spaceships meaning that it will overlap our spaceships actually you know maybe that's not the best idea maybe we want our spaceships to go over top of this font if that situation occurs which it could so let's start by doing this let's say red health underscore text and this is going to be equal to pie game or sorry not pie game we're going to say score not score health underscore font finally got it right third try dot render now we just define this font right we're going to use this font to render some text now the text that i want to render is the following i want to render health colon and then space plus the string of red health so we'll take whatever that number is convert it to a string and concatenate it with help then we need to say 1 for anti-aliasing i'm not really going to talk about that is but you just always put one as the middle argument for our purposes and the color of this text which is going to be white so red health text is health font dot render it's equal to health plus whatever the health is and then one white same thing now for the uh not red text but for the yellow text so we say yellow health text now what we've done is we've created kind of two text objects and we want to draw these on the screen so to draw them on the screen we're going to say win dot blitz we're going to pick well i guess we already know the window we're going to pick what we're blitting which in this case is red health text and we need to pick where red is on the right side of the screen so that means i want to blit it at an x position that is like right at the edge of the screen i'm going to do this dynamically you can hard code a number if you want but the correct way to do this or the way that will look the best is width minus and then red underscore health text dot get underscore width this will get the width of that text and subtract that from the width of the screen so the top left position we're blitting this will be like right at the edge and then i'm also just going to subtract 10 pixels just so this has like a 10 pixel pad from the very edge of the screen where do i want to blend it on the y i'll put it at 10 because it's going to be right at the top of the screen we'll just make it 10 pixels down by having this negative 10 and this 10 we're padding it so it's 10 from the right wall intent from the top wall now we'll do the same thing or a very similar thing for uh for our yellow text so wind.blit we're going to say yellow health text and then where do we want it we're actually going to put at 10 10. reason we can do this is because we don't really care about the width of it because it's going to be the left border that we want padded from the left wall and then 10 pixels down as well from the top so that's what blitting it at 10 10 will do anyways this will give us the red health text the yellow hot text it'll be showing up on the screen so let's try this actually uh we handled the events we're passing in the health yeah we're look very close to done so let's run this and now you can see the health is showing up so we have it in the corner boom move that like that and then notice that the health gets updated but for some reason the health is changing for both of them so i think i just have a small bug so let's have a quick look here uh we have that red health so yellow health minus one red health minus one red hit yellow hit okay we're passing red health we're passing yellow health okay for some reason they're both getting updated so i guess that means that this event must be triggering uh for both of them so let's try to see why that's happening so i'm just scrolling around wondering why this isn't working and i'm realizing that well red health is in both positions here so this needs to change to yellow health because i had red health so obviously it was drawing the same thing so anyways let's try this now run and now if i hit someone only the health updates on one side which is what we're looking for so we're very close to done we just need to handle the situation where someone wins and adds sound effects so let's do someone winning first this is actually really straightforward i'm just going to make a function what this function is going to do is just draw text on the screen that says blank person 1 and you'll see how this works i'm going to say define draw winner we're going to take in some text that we want to draw and then we're going to make a new font so let's go to the top let's go with our other font let's say winner underscore font is equal to pie game like that dot font dot sys font this should be comic sans well you can make whatever you want and then i'm going to make this size 100 and i'll make it nice and large so now we'll use the winner font to actually render the text so we'll say winner underscore font dot render we'll render the text anti-aliasing 1 color white and then we'll draw this onto the screen so we'll say win dot blitz will blit the winner font we're going to do this nice and fancy and have it perfectly center in the middle of the screen so i'm going to go inside of here i'm going to say width over 2. now we'll actually double divide it by 2. i did i do that somewhere else i'm not sure just to make sure we don't get any errors although width over two is an even number so i think that's fine if we do that we'll say width over two minus because width over two again is the direct middle of the screen minus the i need to i've made a mistake here okay let's let's go text draw underscore text equals that we need a variable draw underscore text equals that i don't know why i thought blitting winner font was going to work but draw text is equal to winner font dot render that's better so now we'll say width over two minus draw underscore text dot get underscore width this will get the width of the text so how wide it actually will appear on the screen over two this will put it directly in the middle of the screen because it will take whatever half the width of this is and subtract it from the x position so that way when we draw this it will be perfectly in the middle of the screen i kind of went over this before we'll do the exact same thing for heights we'll say height over 2 and then minus draw underscore text dot get underscore height over 2. again get height is just going to give you the height might be smart to do integer division here but i think this will be fine then we're going to say pie game dot time dot delay and we're going to delay this for 5 000 milliseconds which is five seconds you'll see why but what this will do and sorry we also want to update the display so before we start delaying i'm going to say pygame.display so what this is doing is we're going to call this function when someone wins so for five seconds we are going to show the the winning text and then we're going to restart the game so the reason i'm doing this and i'm not doing it inside of draw window is because i want to just pause the game whenever someone wins show this text and then just restart it immediately after that's why i have this pause if you want to change the pause to be longer or shorter just a thousand multiplied by whatever seconds you want to pause it for and that's how you pick the delay okay so now inside of wiener text here we're going to say draw underscore no not window draw underscore winner and we're just going to pass it the winner text because what this will do is then give it the winner text it will draw it on the screen we'll pause for five seconds it will appear and then we will break now when we break this will bring us to pi game dot quit which would usually quit the game now we can do that for now so let's actually just do that and i'll change it so it just restarts the game so here let's just spam control a bunch of times and make it so that we actually win so there you go boom we hit it says yellow wins appears on the screen wait it's going to close the game in a second and boom go ahead or the game goes goes ahead and closes now if we don't want the game to quit what we need to do is make it so we don't quit the game here but we just restart it how do we restart it how we started originally just by calling this main function since we define any game specific variables in here when i just recall the main function it will redefine these variables and the game will just restart so instead of having pi game dot quit i'll just say main like that but that means that what i need to do now when we actually do quit the game is say run equals false as well as pygame dot quit right inside of here so hopefully that's clear but this means now whenever we press the x it will actually close because if i removed pygame.quit from here and i didn't quit then we would just stop the while loop but we would restart the game whenever you press the x button which obviously isn't what we want so we have that now we can do one last test then we're adding sound effects and we're done so let's do this uh let's just test this out and let's keep going boom yellow wins give it a few seconds and it should just restart the game okay there we go restarts the game we get put back in our original positions we have 10 health we can fire our bullets and we're all good awesome so let's now add the sound effects which are super simple and then we will be done so the first thing that i need to do is load my sound effects uh actually sorry second thing i need to do is load my sound effects first thing i need to do is initialize kind of the sound effect library in python so i'm gonna go to the top here i'm gonna say pygame dot mixer dot init and this just starts kind of like the sound aspect of pie game so that it will work anyways now that we have that we're going to load in a mixer sound which will allow us to start and stop a sound whenever we want so the first thing i'm going to do is i'm going to make a variable i'm going to call this bullet underscore hit underscore sound and this will be when we actually hit something that'll be the sound and then we'll say bullet underscore fire like that underscore sound and now let's load these in so we're going to say pi game dot and then in this case we're going to say mixer dot load and we're going to load from os dot path dot join the start of the pass path is assets and the end is simply the name of what we want so the gun silencer funny enough these are the sounds i've used right the gun silencer is the one for when someone collides and the sorry the gun silencer is for when someone shoots and the grenade is for when it collides so i'm just gonna say grenade plus one dot mp3 and then we'll just copy this line do the same thing but change grenade plus one to be gun plus silencer uh did i spell silence or right yeah dot mp3 so now we have both these sounds and if we want to use them it is really easy to do this all we have to do is go down and i'm just going to make it so that whenever we fire a bullet so whenever this happens we actually make put that sound right so now i'm just gonna say bullet underscore fire underscore sound dot play all right is it dot start or is it dot play i think it might be dot start uh let me look at my other code here so actually no it's i've been lied to it is dot play okay so we're going to play the sound like that so bullet fire sound dot play and the same thing here so whenever we fire the bullets we'll play the sound and then whenever we get hit so whenever we lose health we'll play the collision sound so we'll say bullet underscore hit sound dot play copy that and paste that there so that's it that adds the sound effects this should be our game so let's run and pi game dot mixer has no attribute load okay so let me see what this is actually called um i thought it was called load but i guess it's called something else ah so i've made a mistake this is actually not supposed to be load where is load uh this is supposed to be sound with a capital s so just change that there this happens all the time i just forget the syntax pi game dot mixer dot sound and then this should work so let's run this now with the proper syntax let's run and bullet sound uh unable to open file assets grenade plus one dot mp3 now it looks like i do have grenade plus one dot mp3 for some reason that's not working i'm just going to go ahead and i don't usually recommend doing this but since i don't know the mistake i'm going to try assets slash grenade1 and then we'll just do the same thing here so we'll remove the os.path.join i don't think we actually need it for this specific sound or for the way that we're loading these and then we'll just do that so we'll just kind of you know make the path ourself assets slash grenade plus one and so on so let's try this now see if all is good unable to open file okay so give me one second i will be right back okay so it turns out that there's actually a corruption of these mp3 files of course that's going to happen to me at the very end of the tutorial but i promise you that the code i just wrote and i'll zoom out so you guys can can kind of see all of it i'll just slowly scroll through as i conclude here uh the code that i just wrote so the way i loaded that that's totally fine like even the os.path.join that should work and then to play the sound all you do is dot play so just trust me that this does work for you guys uh for some reason when you download the mp3 file you like they're corrupted as well then just find your own sound effects and just load them in so throw them in the assets folder name them something and then load them i think it's just an issue with downloading the files from github you can't download mp3 files but do that load them in pick your own sound effects they should work with dot play it's a really minor part of the tutorial so i'm not too worried about it but then you should hear the sound effects when you press those buttons and well it does obviously add a lot to the game now i will quickly mention before i leave off here because this is all we're doing for this tutorial but there's a lot more stuff in pi game that you can do the point of this was really just to get you up to speed nice and fast show you how to create a simple game and show you how to do most of the things that you usually want to do you know projectiles moving characters around handling collision all that kind of stuff loading images loading sound effects although that didn't really work and all that kind of stuff and keep in mind like you know usually you can separate things out into different files this isn't perfect what i did but again just to give you an idea and really get you kind of started in python and pie game so if you guys appreciate this tutorial please do leave a like on the video and subscribe to the channel it definitely helps and i hope that this was helpful to you so with that said i will see you in another youtube video [Music]
Info
Channel: Tech With Tim
Views: 796,492
Rating: undefined out of 5
Keywords: tech with tim, pygame tutorial for beginners, python, python checkers tutorial, python pygame, pygame, pygame python, pygame tutorial, python pygame tutorial, pygame games, python programming, python tutorial, pygame tutorial python 3, how to install pygame for python, pygame pip fix, pygame shooter game, how to make a beginner pygame game, pygame for beginners in 90 minutes, moving objects in pygame, collision in pygame, sound effects in pygame, pygame for beginners
Id: jO6qQDNa2UY
Channel Id: undefined
Length: 95min 22sec (5722 seconds)
Published: Fri Jan 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.