Python Beginner Project Tutorial - Turtle Racing!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everybody and welcome to a brand new youtube video so it's been a while since i've done a kind of beginner project something that really anyone can follow along with regardless of their background in python and so i wanted to do one for this video so what i'm going to be showing you how to do is actually create a graphical application so this is not just going to be text although it looks like that right now and what's going to happen is we're going to create a turtle racing program so essentially the user will be asked to decide how many turtles they would like to race based on their answer a screen will pop up as i will show you in one second and then it will race that many turtles by just randomly moving them on the screen now this is a great project to learn about how to build something a little bit bigger than a really simple hello world application i guarantee if you're new to python you're going to learn a ton here i purposely used a bunch of different syntax and functions and kind of showed you how we can lay out a relatively large program for beginners this is not a large program by any means in kind of a nice structured way where everything is just done in kind of the proper format so anyways let's go ahead and get started here i'm just going to show you a demo of what we're going to be building so it says welcome to turtle racing please enter the following information how many turtles would you like to race you can enter between two to eight turtles i'm going to select eight when i do this it's going to open up the turtle window this is built into python there's nothing fancy you need to install it's going to initialize all of our turtles and then it's going to start racing them on the screen so it looks like the red one is going to win here let's see and oh maybe not so it says here the winner of the race is pink and then it waits five seconds and then it stops now i will show you how we can run this multiple times if you'd like to do that that's the basics behind this program now let me show you one more time if i race say three turtles notice how they are evenly spaced out on the screen so i'm gonna be showing you how we can do that and there you go they race nice and it says the winner is orange awesome so let's dive into this video after a quick word from our sponsor before we get started i need to thank the sponsor of this video which is alco expert algo expert is the best platform to use from preparing for your software engineering coding interviews and has the highest quality coding interview practice questions with over 140 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 walk-throughs for each and every problem algo expert is the best resource to use to ace your coding interviews aligoexpert also has a data structures crash course coding interview assessments and a 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 clicking the link in the description and using the code tech with tim for a discount on the platform all right so let's get started by talking about what you're going to need to follow along with this tutorial you are going to need some type of code editor and an installation of python those are the only requirements here so if you have python already installed on your system which i'm assuming all of you do at this point in time then open up your favorite code editor it could be sublime text that's what i'm using right here or if you're not even sure what i'm showing you you've never seen this window before you don't even know what i mean by text editor just open up your standalone standard idle like this and for you to follow along with me here just go to file new file write all of your code in a file like this save it with some name it's very important that you do not name your file turtle do not name it turtle if you name it turtle you can potentially have some problems and you're going to go in here save this file as whatever you want that's not named turtle and save it in whatever location you want and then whenever you want to actually run your code when you're inside this file you can press the f5 key on your keyboard or you can go to run and then press run module and well that will run your python code now i'm going to be working in an editor called sublime text this is a free text editor i'll leave a link to it in the description what i've done here is i've created a new file it says turtle race tutorial dot pi and the way i'm going to be running my file is from my command line so i'm going to go to my cmd if you're on mac this would be your terminal i'm going to use the python command followed by the name of my file so in this case it's going to be turtle race and then tutorial dot pi and then this will actually run my file for me notice i've saved my file on the desktop that is why the path for my command prompt is on the desktop hopefully that gave you enough information so that you are confident to follow along if all of this makes no sense just open up idle and just write python code as how you normally write it you don't have to work in this text editor that i am here anyways let's go ahead and get started so the first thing that i want to do here is i want to ask my user to input the number of turtles that we are going to have so what i'm actually going to do here is i'm going to create a function if you've never seen a function before i'll explain them they're pretty straightforward but i'm going to say define and the name of this function is going to be get underscore number underscore of underscore and then we'll say racers like this or turtles whatever you want to call this and then inside of here this is where we are actually going to ask the user to insert the number of racers that they want to have now the reason you're going to see me kind of write things in this way in different functions and kind of different blocks is because it really separates out what every single aspect of our program is doing and it's just good practice when you're writing code to really have all of the different separate things happening kind of in different areas so later on if something goes wrong or you want to add something or change something it's really easy to do that you're not looking through a huge mess of code and well you'll see how this kind of evolves as we go through here so what i want to do is i want to ask the user for a number so i want them to insert a number between 2 and 10 and so i also need to validate that the number they're typing in is correct so what i'm going to say is racers is equal to zero and then i'm going to say wow true now the reason i have a while loop here is because i want to continue to ask the user to insert a number until they insert a valid number so if they insert something invalid then i'm going to keep asking them and say hey no that wasn't valid give me something that's valid because we can't start our program until we know how many turtles we're going to be racing so i start with racers equals zero i say well true now i'm going to use an input so i'm going to say racers is equal to and then input like this and i'm going to say enter the number of racers and then i will do kind of a little 2 to 10 thing here to indicate the fact that i would like them to type a number that is between 2 to 10. now you don't have to do it like this you can write whatever you want this is what i'm going to prompt the user with and then notice that here i've added a space so after my colon i have a space the reason i have a space is because the user starts typing immediately after this prompt so this text will be printed to the screen so i want to separate it from the colon so that it doesn't look like they're typing like right beside this line there's like a little bit of a space anyways what i'm now going to do is i'm going to check if this what they inputted is a number the reason i need to check if this is a number is if the user didn't input a number obviously that's invalid but also i want to convert what the user types in into a number if i can do so so in python by default when you use this input statement it's going to capture whatever the user types into the console and convert that into a string so we need to take that string and potentially convert that into an actual integer a numeric value so that we can use that in our program so i'm going to say if racers. and then is digit this is a method you can call on strings and this will tell you if the string is completely numeric or not so if the string is numeric then what that means i can do is i can convert this into an in so i can say int racers if you tried to just do this line without checking beforehand if it was numeric then this would crash the program because if you had a string that was typed in that was not numeric you say you try to convert say ins of tim to a int right you're trying to convert the string tim into an int this is inval that's going to crash you you can't do this so anyways let's move on now if this is not the case so if erasers are or if what the user in input sorry is not a digit then what we want to do is tell them hey this is invalid please try again right so i'm going to print and say input is not numeric dot dot try again exclamation point and then i'm going to say continue now what this continue does is immediately brings me back to the beginning of the wall so we don't really need this continue well we will based on what i write next but think of it this way as soon as we hit this statement it immediately jumps right back up to the top of the loop so anything below this had a print statement saying like print hi this print statement wouldn't run if we hit this continue before this print statement so that's why i have the continue here all right so if the racers is a digit so if what they inputted is a digit then we are going to convert it into an integer which is valid otherwise we'll tell them it's not numeric they need to try again and then we'll continue now if we make it past this so we don't hit this else and we did make this conversion now we want to check if this number is within the range of 2 and 10. so i'm going to say if 2 is less than or equal to racers less than or equal to 10 then what i will do is i will just return the racers like that otherwise i will tell them that this number is not valid so the idea here is i check if racers which is now a number that's why i wanted to convert it to a number so i could do this comparison is less than or equal to 2 or less than or equal to 10. so if it's within our range of 2 to 10 this is fine what i will do is return racers so whatever the user typed in we're going to return that from this function which means whatever called this function will now have access to it otherwise though if this was not valid what i want to do is i want to print number oops not in range 2 to 10 try again exclamation point and then i could put a continue here but there's really no need to do that because nothing comes after this continue in this while loop and so by default we will just go back up to the top the reason i have to continue here is because i don't want to check if the number that is not a number right so what the user typed in i don't want to check if that's between 2 to 10 because if i do that and we haven't converted this into a number we're going to get an error let's say you know what the user typed in again was tim i can't check if 2 is less than or equal to tim this is just undefined this operation makes no sense and so that is why i'm continuing to make sure if i don't get a valid number i don't do this comparison and crash my program all right so now we have this function so i'll show you how we can use this right we can just call the function so get number of racers and we can say something like racers is equal to get number of racers and then we can just print out racers down here now what will happen is all of the code that we wrote inside of here notice it's indented after the colon right uh it's going to run all this code when we call the function and then as soon as we hit this return statement what will happen is we will actually return back to where we called this function so back to this line and we will pass whatever the value of racers was so racers will be equal to down here whatever is returned from this line so whatever number the user typed in that was numeric and between two to ten then i'm going to print out those number of racers that the user typed in and that's kind of the start of our program then we've got a few more stuff a few more steps sorry to do after that so let's try running our program i'm going to say python turtle racetutorial.pi again if you're an idle just press f5 and come on enter it's just going to work okay something's wrong with my terminal python turtle racetutorial.pi okay enter number of racers 2 to 10. let's enter 5 and then it prints out 5. now let's try something involved let's try tim now it tells me input is not numeric try again let's try uh joe not numeric try again let's try 11. number is not in range let's try 10 boom that works we get 10. awesome so this is indeed working we just did a few tests here and you can see that down here we are getting access to whatever this function returned so now that we have the number of racers what we want to do next is actually set up our turtle screen so i will show you what i mean by that but let's start by importing the internal module so the eternal module is built into python and this allows you to perform very basic 2d graphic operations with this thing called a turtle so you'll see it in a second but essentially it's like a little kind of header on the screen and you can kind of move it around it will draw lines and it's a really great way to just learn the basics of python in a nice visual way so now we have the number of racers now we've imported turtle and let's actually just see what happens now when we run the program after importing turtle so we're going to run this uh let's import our number of racers we can go four and we actually see that nothing happened i was thinking the turtle screen might pop up but it's i think it's because i haven't used this module yet so anyways that was a poor example what i'm going to do next is show you how we can create a turtle screen so ignore that last example uh what i was expecting to happen didn't happen often times when you import a module like something will happen when you import it so what i'm going to do now at the top of my screen is i'm going to define first of all the width and the height that i want my turtle screen to be so usually whenever you're working with graphics you need to define the size of a screen or the size of the canvas you're going to be working on so in this case i'm going to say in all capitals width comma height is equal to and then 500 comma 500. if you haven't seen this notation before this means width is equal to 500 height is equal to 500 you can separate as many variables by commas as you want and then do the assignment with commas as well so the reason i'm doing this in all capitals is because these are constant values so in programming whenever you have a constant value in a language where you can't explicitly define that you usually have all capital letters to denote the fact that this value width and this value height will never change they're just here so that we have easy access to the width and the height all right so now that we have the width and the height we want to set up the turtle screen so we're going to start by creating a screen so we're going to say screen is equal to and then turtle dot and then all capitals screen now what this is going to do is initialize a screen for us with this turtle module and then we can kind of set some properties of the screen the first of which is going to be the width and the height so now that i have my screen i'm going to say screen dot and then this is set up and here we're going to pass the width and the height so this method right here takes two arguments a width and a height of the screen and then it makes the screen that size so now that we have that let's run the program and let's see what we get so python turtle ray stop high and notice you can see a screen pops up here immediately and then it's asking me to input the number of racers so i can input say 5 and then the program ends and the screen automatically closes great but when i do this notice that we get python turtle graphics as the name of our window we might not want that we might want to change the name so let's actually go ahead and do that so i'm going to close this i probably should have left the cmd open but that's fine and now i'm going to say screen dot title and in here i'm going to put whatever i want the name of that window to be so i'm going to make mine turtle racing exclamation point now let me go and open up my command prompt again uh you can kind of ignore what i'm typing i'm just trying to get to where my file is so python turtle race tutorial dot pi when i run this notice now the title has changed to turtle racing awesome so let's just input a number and end the program there let me make this guy a little bit smaller okay so now we've gotten the number of racers we have set up the turtle screen and what we want to do next is actually create our turtles we want to start racing them on the screen so i'm going to start by showing you kind of the basic commands of a turtle so how you kind of move a turtle around the screen some of the things that are associated with it and then we'll create a bunch of different turtles and then obviously erase them so what i'm actually going to do though is i'm going to take all of this code related to the turtle stuff so the screen setup the screen title all of that i'm actually going to move that to underneath where my racers are and in fact i'm actually going to make a new function i change my mind i'm going to call this a knit underscore turtle and inside of this function we're going to set up everything related to our kind of turtle screen now the reason for this again is that we just want to kind of structure our program nicely so we won't show the turtle screen until we call this a knit turtle function so after we get the number of racers then we can pop up the turtle screen because i don't really want it to be shown until we've picked the number of turtle erasers that we have so after we get the number of racers we can say a knit turtle that will just run all of the code in here so we'll set up our turtle screen so let's actually go ahead and run this and let's see what happens notice that the turtle screen hasn't popped up this time but then when we type 4 it kind of pops up really quickly and then it closed because as soon as we pop it up the program ends there's nothing more that we need to do we're on a good start now that's kind of what we wanted to do okay so now i'm going to show you how we can kind of move a turtle around the screen so to do this you need to start by creating a new turtle object so to create a new turtle object what you need to do is say and in this case we'll just say racer is equal to and then turtle dot and then with a capital t this time turtle so what this will do is actually create kind of a drawing object for you on the canvas that you saw that white canvas that popped up and then what you can do with this is you can move it around so i'm going to say eraser dot and then just to show you one method you can use forward i'm going to move it forward by 100 pixels now i'm going to do something here that may seem a little bit confusing but i'm going to import a module called time at the top of my program and down here this is really the only new code that we've added right after i move my racer forward by 100 pixels i'm going to say time dot sleep and then five what this will do is pause the program for five seconds so that after we move our turtle we have a second to actually see where it went we don't just immediately close the turtle window although we may or may not do that um immediately close the turtle window anyways we'll see here after this happens so let's run this code right now and let's see what happens we'll say 4 and then notice it opens this turtle window and then it moves this kind of pointer over here by 100 pixels and then it closes obviously because now we are no longer sleeping so hopefully that kind of made sense but you would have seen uh let's run this one more time that it opens up the window it moves our little pointer here which funny enough isn't actually a turtle right over 100 pixels and then it closes so this is one of the methods you can use with your turtle the turtle will start in the middle of the screen the turtle is really that drawing kind of arrow that you saw and every single time you move it it will create a line so you don't only have to move it forwards you can move it backwards and you can also change its direction so you can set it to move maybe in 90 degrees you can set it to go left you can set to go north east west whatever direction system you want to use you can set it to go in that direction so i can say racer dot left and then i can make it go left by 90 degrees and then i can say racer dot forward move it forward 100 again and then i can say racer dot and then let's just go left we can go left another 90 degrees and then we can say racer dot backwards is it backward or backwards well i guess we'll see when we run this and then by 100 pixels so let me run the code now python troll erase stop hi and there we go oh so it's saying turtle object has no attribute backwards that is because this is backward not backwards with the s so just don't add the s for the plural there and let's give this a shot now so python turtle racer and there you go that's what happened see we went right oh sorry it went straight then we went left then we turned uh left again but then instead of going forward we went backwards and so we went the other direction so you can kind of mess around with these uh forward left there's also right and inside of these methods here what you're placing is at least inside of the right method is the angle at which you want to turn the turtle so if you wanted to turn 90 degrees you put 90. if you want to turn 180 degrees you put that if you want to turn 45 degrees you put 45 i'll let you guys mess with that on your own and then this the number of pixels is well how far you're moving the actual turtle so when we open up the turtle window and let me time that sleep for say 20 seconds here just so we have lots of room so i can explain kind of the coordinate system so let's run this let's open up the turtle window all right so this turtle window is 500 by 500 pixels so the height is 500 pixels and the width is 500 pixels now the very middle of this turtle canvas it has the position of zero zero so the top of the canvas has a position of 250 the bottom of the canvas has a position of negative 250 the left of the canvas is negative 250 and the right of the canvas is 250. let me open this up again the way this works right is that if the middle is 0 0 and we have a height of 500 then the top y position on our canvas when we're talking about just a standard 2d graph is going to be 250 whereas the bottom y position is going to be negative 250. so as you increase your y you go up as you decrease your y you go down as you decrease your x you go to the left as you increase your x you go to the right hopefully that makes sense and again negative 250 and positive 250 the reason that's the top and the bottom is because the height is 500 i just divided 500 by two and then applied a negative to one of the bounds hopefully that's making sense but that is the coordinate system the reason that's important is because when i say i move 100 pixels uh well we need to understand where that's actually going to move us to and what scale this is on so when i'm moving 100 pixels i'm really moving one-fifth of either the height or the width of the screen depending on the direction that i'm moving in so we're going to erase our turtles going up the screen but you could totally erase them going to the right going to the left whatever direction you want now a few more methods that are useful when we're talking about turtles here are things like the actual icon that's representing the turtle as well as the speed of our turtle so what i can do here is i can change my racer speed so i can say racer.speed and then set this equal to say 2. now let me actually check what the racer speeds are okay so i just checked what the different turtle speeds are here you can see that these are the potential speeds we have so we can insert a speed between 0 to 10 and let me just show you this method again we have the turtle object that we've created dot speed so we can set the speed of it to be slow or fast because you kind of saw how it's moving around the screen right so if we go here oops let's go back to google we can see 0 to 10 where 0 actually means we're going the absolute fastest we can possibly go 1 is the slowest and then 10 is fast so really it's one to ten and then if you input zero it's saying just go as fast as the turtle can possibly move so let's try putting in a value of say two or even one and let's see how slow this turtle gets when i change its speed so i change its speed let's run and now notice it's moving much slower than it was before there we go that is our turtle oh yes it's going right now because i put that right 90 degrees awesome so let's wait for this to close and then i will show you that we can change say the color of the turtle and we can change what the actual icon looks like and all of that in fact i'm not going to wait for it let's just do it now so if i want to change the icon of the turtle what i can do is say racer dot and then i believe i'm actually going to have to look at my other screen here for a little cheat sheet this is the shape that's what it's called so i've been referring to this as the icon it's actually the thing you're seeing on the screen but there's a bunch of different shapes that you can choose for your turtle so i want to make mine turtle but some other valid ones i think are circle we have arrow and then you're welcome to look up the other possible shapes that you have for turtle i can't remember all of them but i know that at minimum two of them that exist are turtle and circle and then obviously there is arrow as well so sorry those are the three that i know that exist okay so let's change this to a turtle now and let's see what happens this time when i run my program i'm going to remove the sleep because i've slowed down the turtle so hopefully we have enough time to see it now so let's run this enter some number and now notice we get an actual turtle moving around the screen awesome so that is good now i will show you how we can change the uh color of the turtle so to change the colors pretty straightforward you can say racer.color and then inside of here you can put a string that represents the color you want to change this to so there's like a ton of different possible colors here i won't go through them all but for example one is scion we could do red we could do green we can do blue we can do yellow black orange so on and so forth so let's just change this to scion so let's run our code here and notice that now we get a cyan turtle and that the line that it has is psion as well now there's a ton of other stuff you can do with turtles if you want to see all of that i would just recommend you just look up turtle python like that and then you can see if you go to the turtle documentation here that there's a whole list of all of the possible stuff that you can do with your turtle so i'll be showing you some of this but i won't obviously go through all of it okay so the next thing to show you is what is called turtle.pen up so whenever the turtle's moving around the screen you notice it was kind of drawing that line right and we're calling that the pen so as the turtle moves it's kind of a pen and just drawing this line on the screen now if we want it to not draw the line but we still want it to move we can bring its pen up so we can say racer dot pen up like that and now you're going to notice when i run this program after i've moved the pen up is that as we move this turtle around the screen no line is being drawn right because it's pen is up so what i can do is i can move the turtle with its pen up i can put its pen down and then i can continue drawing so let's copy this line let's move the turtle uh forward by 100 left by 90 and then let's put its pen down so we're going to say eraser dot pen down so let's do this now python here and now notice that as soon as it turns that corner then the pen goes down so all this stuff i'm showing you you can change at any point in time you don't have to change it before the turtle starts moving or something like that all right so now i've showed you pretty much everything i need to in terms of the different methods for the turtle object just keep in mind you can make as many turtle objects as you want so i said racer equals turtle.turtle i can make a second uh turtle right it's a racer two and then i can move these turtles in different directions so just to give you a quick example we can copy all of this and then we can just change this to be say racer2 and we'll just make racer2 a different color so instead of psion we'll make it say brown like that maybe we'll make it speed a bit faster and then we'll change it so it goes forward like 150 just so you can see the difference in these two terms so let's change that to be 150. again notice i just had racer 2. we can kind of copy this and put it down here to separate these things out all right so let's try this now so let's go python turtle racetutorial.pie uh let's enter a number of racers three and then notice the first racer is going to move around and then our second guy kind of start moving really quickly right because we wrote all of this code after we wrote this code so i'm going to delete all of this just wanted to show you that and now what we are going to do is we are going to pick the colors of the different racers that we have so once we know how many racers we have we need to kind of create all of these turtle objects and we need to pick their colors so i'm going to create a list of colors up here in all capital and i'm just going to type out a bunch of them i have a list on my other monitor in case you see me looking over there so i'm going to say red we're going to say green we'll say blue uh we'll say orange we have if i can get my cursor here correctly yellow we have what's another one black purple we then have pink and did i do yellow yes i did what's the last one we have brown and cyan okay brown and then scion now note that there is a lot more colors than this i'm just doing 10 for right now so we can have at most 10 turtles so now that we have all of these colors we kind of need to pick after we've gotten our number of racers what turtle colors we actually want to use so i'm going to show you a cool way that we can do this so we can randomly select a bunch of colors from this color list that are unique so at the top of my program i'm going to import random all of these modules are built into python you don't need to install them or anything like that and then down here what i'm going to do is i'm going to say random dot shuffle and i'm going to shuffle my list of colors so all this capital list right here now what this is going to do is it's going to take the list and just randomize all of the items inside of it so i have no idea where these items are going to go but all of the items that i have here will just be kind of randomly placed around in the list then what i'm going to do is i'm going to select the first number of racers item from this list that that are there we'll use that as our color so i'm going to say colors is equal to and then colors and then this is going to be a slice up to the number of racers that we have so let me just quickly explain this we've gotten the number of racers we've initialized the turtle we're shuffling that colors list so just randomizing the order of all the elements there and then what this does is this gives us the first racers item from the list so if we had a list say one two three comma four and then we put this little slice operator this is what it's called when you use the colon and we said up to say 2 what this would give me is the first two elements in this list so i would get a new list that looks like 1 comma 2. now if i did the slice of say 3 this would give me the first three elements so one two three that's kind of the basics of a slice so the reason we're doing that is we're randomizing the list and then just taking the first say number of elements that number is equal to whatever the number is the user types in so now let me show you this we're going to print the colors after the user types in the number of turtles they want to race so let's do this python turtle race let's in insert five and then notice it kind of popped open that turtle window closed it and then it printed yellow purple green orange brown now if i do this again and i type five you're going to notice we get different colors right and they're in a different order so black red orange brown scion now this 100 will always select unique colors for us so we'll never have turtles that have the same color all right now that we have all of the colors we want to create all of these turtles so we're going to make a new function here we're going to say define and then create underscore turtles now inside of here we're going to create a list of turtles and then we're going to kind of place them on the screen in their starting position so ideally we want to have all of the turtles evenly spaced out at the bottom of the screen and kind of pointing upwards ready to start racing so let me show you how we do that well the first thing that we need to do here is we need to determine what colors our turtles are going to be and how many turtles we're going to have so this function as a parameter is going to take in colors so we are going to pass this function when we actually decide to call it the number of colors that we have and then what that's going to are not the numbers sorry just the colors that we've actually selected and by having this list here we will also know how many turtles we have because the number of elements in this list will tell us the number of turtles that we want to race so now what we're going to do is we're going to say that turtles is equal to an empty list then we're going to loop through all of the colors that we have and for every single color we're going to create a turtle and add it into the list the reason i'm creating a list is because i don't know how many turtles i'm going to have so i can't just define variables with like you know i can't find four variables for four different turtles or five variables for five different turtles i need to kind of dynamically create these turtles because again i don't know how many i'm gonna have so i'm gonna loop through now all of my colors i'm going to say 4i comma and then color in enumerate and this is going to be colors and what enumerate does is it gives me the index as well as the value of all of the elements in colors so if i'm looping through colors let's say like red and then green then what's going to happen is i'm on my first for loop iteration i will be equal to zero that's the position of this color color will be equal to red and that's great then on my next iteration i will be equal to one and color will be equal to green and if i had one more iteration say this was blue then i would be equal to two because this is the third element where the second index slash position and then the color will be equal to blue so that is what enumerate does gives us both the index and the value now what i want to do is create a turtle so i'm going to say racer is equal to and notice you can name these variables whatever you want and i'm going to make this equal to turtle.turtle just like we saw previously and then immediately i'm going to change the color of this turtle to be whatever color this is so i'm going to say racer dot color and i'm going to make this oops if my sublime text stops crashing okay it's crashing so i'll be back after this stops crashing alright so i am back that was really annoying sublime text just crashed on me but i have eraser.color and i'm going to set this color to be equal to color the reason i'm setting it equal to color is because this will be a string this string will come from this list of colors right here and so every one of our racers will be a different color then what i need to do is set a few other things i want to set the shape so i'm going to say racer.shape and this is equal to a turtle then what i want to do is place this racer in its starting position now before i do that i'm going to show you where they are placed initially but i also want to turn these racers so i want to say eraser.left by 90 degrees now the reason i'm doing this is because by default the kind of arrows or whatever are pointing to the right so if i want them to point upwards because i want to race my racers upwards and my turtles upwards then i need to turn them left by 90 degrees so i'm going to take my eraser or make my eraser which is just a turtle i'm going to set its color i'm going to set it shape i'm going to set it's kind of heading so it goes and is facing upwards and then i'm going to add it to this list so i'm going to say turtles dot append and then i will append my eraser this way i have access to all of my turtles and then later on i can actually say move these turtles forward right and we'll move them by a random amount and that will kind of simulate these turtles being raised now i'm just looking at my other screen here one more thing that i'm going to do here is i'm actually going to put my racers pen up so i'm going to say racer dot pen up i'm then immediately going to say racer dot pen down and inside of here i'm going to set the position of my eraser so we'll just say set pause and we'll do that in one second all right so now let's run this code here so python turtle racetutorial.pi let's insert our number let's say three and what happened ah well we need to call this function if we want to see anything happening so after we get our colors let's call createturtles and let's pass our colors so now we'll have all the colors here we'll loop through them and create our races for each all right so let's run this python turtle race let's go five and notice when i do this it kind of spins up five turtles they you know spin to the left they're all different colors and then it's done so obviously this is not ideal right all of my turtles start in the middle of the screen and so i need to move them so they are at the bottom of the screen now i could move them like backwards turn them left move them to their correct position but that's kind of a pain so there's this method for our turtles called set position uh actually let me make sure it's called that yes it's called set pause so racer dot set pause and this takes an x and y value and will set the position of your turtle to well this position so this is why i'm putting the pen up then i'm going to set the position then i'm going to put the pen down so when i move this turtle to its position i don't draw a line from the middle of the screen to wherever it goes because that's just not optimal it's not ideal that's not what we want to do here so inside of set paws i need to choose an x and a y value for my turtle now the y value is pretty easy because all of my turtles will start at the same y and then they'll kind of increase their y as they race upwards so we know what the y value will be or we can just pick some random y value but what is the x value going to be well i want to space these turtles out completely evenly right so let me open up my kind of windows ink pad here where even is windows ink okay so i've just opened up paint here i unfortunately couldn't find the windows ink thing that i normally use i don't know where they would have hid it from me but anyways apparently it's gone so go easy on me i'm just using my mouse but i'm going to illustrate what we're going to do here so we have our canvas right now our canvas is of size 500 by 500 but to make math a bit easier we're going to say it's 400 by 400 again my mouse is really hard to draw with okay so 400 by 400 now we want all of our turtles to kind of be placed near the bottom of the screen so to pick this position is pretty easy we can kind of just take like the height of the screen we can divide it by two we can add a small value to it and then we'll say alright well that's where we want to place the turtles at that negative coordinate because right here in the middle is 0 0 right so as we go down this is negative so if we place that negative 200 they'd be like right at the bottom of the screen so we can move it up like 10 pixels and then that would bring us to this kind of red line that we have right here now the question becomes though what are the x values of our turtles so obviously we want our turtles to be kind of spaced out if we have two turtles we probably want them somewhere like here and here right want them equal distance from each other and then equal distance from the edge of the screen now i know this isn't exactly equal distance but hopefully you're kind of getting the idea if we have three turtles we want one guy in the middle one guy here and one guy here this way they're equal distance from the edge of the screen and from each other so how do we figure out the x positions well what we actually need to do is we need to figure out first of all the spacing between our turtles then what we can do is we can start our first turtle at whatever the spacing amount is we can then add whatever the next spacing is toward our next turtle and then our next spacing and so on and so forth so how do we figure out the spacing between the turtles well we actually take this number right here sorry this number right here which is the width of our screen and we divide it by the number of turtles that we have plus one so i want you to see this example if we take 400 and we have four turtles a lot of people would say well the spacing between each turtle should be 100 pixels now the reason why that would actually be incorrect is because that would assume the first turtle starts at the far left hand side of the screen so if i put my first turtle right here and then i go 100 pixels over my next turtle is at position 100 right if we're talking about the x then my next guy comes over here and he's at 200 and then my next guy comes here and he's at 300. it's really hard to do a three clearly this is my attempt at a three okay so 100 200 300 and then this first guy's obviously at zero so we don't want that we want to kind of shift this whole line over so there's equal distance between all of the turtles and the edge of the screen so what we really need to do is we need to divide this number by five and then we need to start our turtle at the first spacing position so if we take 400 and we divide this by five oh god this is testing my math skills 400 divided by 5 should give us a value of 80. yeah i think 80 is correct 8 times 5 yeah 40 400 yeah okay 80 is correct so now if we do this at 80 let me kind of erase all of this here we'll say that our first turtle gets placed at position 80. so the first guy goes right here uh should i even attempt to do an eight okay we have eight zero then our next guy is going to go at 160 and then we'll move over again and then our next guy is going to go at 240. our next guy will go at 320 and then this will be perfect we'll have our four turtles they'll be equal distance from the edge of the screen and equidistance from each other now i know this seems like they're not equal distance because i've kind of drawn this not to scale but that's the idea behind this so hopefully this long explanation gave you the idea of what we're doing we're going to divide the value that we have here by the number of turtles plus one then we're going to place the first turtle at spacing position so whatever the spacing is so starting at 80 the rest of them will go up by the increment of spacing every time so we'll leave that kind of open in the background in case you need to refer to it again but this means we are going to set the position and we need to figure out the turtle spacing so i'm going to say spacing x is equal to and then the len of colors this is the number of turtles that we have right plus one we're going to put these in parentheses and we're going to start by dividing the width by 2. so we're going to say width divided by 2 sorry not width divided by 2 with divided by the length of colors plus one so whatever our width is we divide it by the number of turtles plus one which is really just the number of colors that were given to us and there we go so now where do we want to start placing our turtles well what i was showing you before is i was starting replacing at 0 80 so on and so forth the only issue with that is that when we're at the left so we're to the left of the middle of the screen we're at a negative coordinate right so really when we're drawing the kind of coordinate axes here this is zero zero so as we're over here we're in the negatives so that's fine all that means is we need to add the negative width over 2 as our starting position to all of these right here so the first position for our turtle will actually be at negative width over 2 plus this value right here the reason that will work is because we will subtract this by negative 200 and then negative 200 plus 80 that will be equal to what is this 120 negative 120 then we will go and be equal to negative 40 then we will be equal to 40 then we will be equal to what's 80 plus 40 120 and that will work and that will still give us the equal distance and it will just kind of translate everything over to the left which is what we want it to do so hopefully that's making sense we just need to account for the negative coordinate system so we're going to set position at negative width over two and then we're going to add to this i plus one let's guess why we need to do that in a second multiplied by and then the spacing x so this will be our x position and our y position will be equal to negative height divided by two plus 20 pixels now this is kind of an arbitrary value i'm deciding i'm saying we want to be 20 pixels from the bottom of the screen so we take the negative height divided by 2 and add 20. the reason we have the i plus 1 is because we start indexing at zero so the first color is zero really we wanna make that one because remember we want to place the first turtle at the first spacing position so negative width over two plus whatever the spacing x is that's where the first turtle should go then the second turtle well that will be a one so that will give us two so then we'll be at the second spacing position then the third then the fourth so on and so forth so this should place our turtles in the correct position let's see if it does so so let's run our code here and let's say we want to have eight turtles so we have eight turtles notice that now we're going to move the turtles they are perfectly aligned on the screen and they have equal spacing between each other and between the edges so that's awesome now all we need to do is just return our turtles like that and now that we've created the turtles we've placed the turtles we've picked our colors and the number of turtles that we have we can start finally erasing them on the screen all right so now what i'm going to do is create a new function i'm going to call this function race and this function race is going to take in our colors now i'm going to change kind of the flow of our program a little bit let me zoom out here so you guys can kind of read more of what's going on so right now what we're doing is we're getting the number of racers we're initializing our turtles we're picking the colors and then we're creating the turtles that's great but i don't want to create my turtles until i'm ready to erase them so i'm going to take this create turtles kind of function call here and i'm going to put that inside of this race function now the idea is that we're going to pass the colors to race and then race will create our turtles for us so we'll say turtles is equal to and then create turtles because this function returns the turtles so then inside of here we will create all the turtles using our colors and the reason this is important is because i want to know what color every turtle is and by having access to colors and turtles i can do that so now rather than calling create turtles down here we're just going to call race so we're going to say race and then colors and then this will create our turtles for us and then in here we can race them so after i create my turtles i want to start racing them i want to start moving them so i'm going to say well true and then i'm going to move all of my turtles one by one now the idea behind this is that we don't know how long it's going to take us for our turtles to get to the top of the screen so what i need to do is have a while loop because i need to keep moving them until eventually one gets to the top of the screen so inside of here i'm going to say four racer in turtles and then what i'm going to do is move this racer so i'm going to say racer dot and then move and sorry this shouldn't say move that's actually going to be racer dot forward because it's now facing the correct direction it's facing up so when i move it forward that's the direction it's going to go in so racer dot forward and then i want to move it forward a random amount so i'm going to say move is equal to or maybe distance is a better variable name distance is equal to random dot and then rand range and inside of here we're going to put the minimum and maximum amount we want the turtle to possibly move at every iteration so i'm going to say 1 comma 20 and what this means is every time i decide to move my turtle i'm going to move it by either 1 or 20 pixels or sorry between 1 to 20 pixels so it will randomly generate a number that is between 1 and 20 and move the turtle that amount that's what rand range does so you can make these values whatever you want the larger you make this minimum value the faster your turtles are going to move and obviously the larger you make this one the higher probability your turtles are going to move faster but really this minimum value will dictate kind of the slowest speed of the slowest turtle right so just keep that in mind i like to keep it at one so that the race kind of looks like they're like kind of inching forward rather than having big jumps every single time anyways we're going to say racer.forward we're going to move it forward the distance now once we've moved our racer forward what we want to do is check if this racer is kind of past the finish line so the reason we're looping through all of the turtles first of all is because we need to move every single one of them we have a list of turtles right we've created all of these turtles here stored them in a list now we need to move every single one of them so we loop through all of them and then we move them now for every racer we check if it's past the finish line so i'm going to say x comma y is equal to racer.pause what this does is give me the position of this turtle so i know the x and the y i don't care about the x i just care about the y i'm going to say if y is greater than or equal to and then height and this is going to be divided by 2 and we'll subtract 10 here then what i want to do is i want to say that this turtle crossed the finish line that it was the winner so to do that i'm just going to return this turtle's color so if this turtle passed the finish line then it is the winner what this function is going to do is it's just going to return whatever the winning turtle is it's going to return the color of the winning turtle so we'll say return and then here we will return and this is going to say colors at index i now this may be a bit confusing but the idea here and oops index i i can't even use that um okay i'm going to show you a different way to do this i thought i had coded this in a different way i'm going to say colors at and then this is going to say turtles dot index turtle so this may be a bit confusing if you guys haven't worked with lists before but this is the rationale we want to find the winner or sorry the winning turtle color want to know the color of the winning turn so to do that we need to access its color now i don't think there's a way to get the color of a turtle from the actual turtle object i may be wrong on that but all we have access to here is just the turtle right we have the turtle that we're moving that's all we have so this kind of turtle.turtle that's all we have so the question then becomes okay how do i find the color of it well i have the colors of all of my turtles here so what i can do is i can find which turtle or the index of the turtle that was the winner and then i can use that same index to figure out the color of it in this colors list so think of it this way if i have a list of colors i have like blue and red and then i have my two turtles right so let's just say i have turtle turtle one and i have turtle two well turtle 2 is at index 1 right so we have index 0 and index 1. so turtle 2 is at index 1. so if i can find the index of this turtle all i have to do is reference that same index in my colors list and that tells me the color of it right same thing for turtle one well turtle one's at index zero its color must be index zero in the colors list this expands with any length of turtles so what turtles.index does is notice this is the name of the list i'm then passing the turtle that i'm looking for the index of it tells me the index of this turtle so and sorry this should be changed actually to be racer that's my bad i was probably confusing you guys there but we have access to the turtle so we say turtles.index racer gives us the index of this turtle object in the turtles list we then use that same index on the colors list to reference the color of that turtle and we return it so not really much more i can explain there that's probably the best that i can do for that we're going to return the actual color now that we have the color down here we'll say winner equals race and then we can just print out winner the idea being that this function is only finished once we return this color so just in case you're aware or just in case you're unaware sorry in a while loop whenever you return something or just in a function in general as soon as a return statement happens the function immediately stops so even though this is inside of a while loop the while loop will stop running as soon as one of the turtles has one so let's just run this code let's just see if this works then i can explain to you some more kind of details about this so let's go here python turtle race let's go with five turtles so we're going to create our five turtles and then they're going to start racing so they kind of start racing up the screen notice that they're drawing every single time and then boom it says pink the reason it says pink is because if you saw pink was the first turtle to cross the finish line now it's worth noting here that there is a little bit of a bias in the uh the first turtle so the very first turtle has a very very small probability of finishing uh earlier than all the other turtles like it has a better chance of doing that in a sense because it's the first turtle that we move we have to move the turtles sequentially like we can't move all of them at the exact same time so we move the first hurdle then the second turtle then the third turtle then the fourth turtle we check if any of them are past the finish line whatever one crosses first we say that's the winner so it's just a higher probability that the very first turtle we move will finish first so the last turtle kind of has you know the least chance of winning but based on this randomness here uh it ends up kind of counteracting that in some type of sense so hopefully you get what i mean i'm not going to worry about that for this problem right here if you guys were concerned about the fact that one turtle has like a little bit of bias which it kind of does what you could do is you could see if one turtle crossed the finish line and then if a turtle crossed the finish line you could still move every other turtle and whatever turtle moved the furthest so it was like the furthest past the finish line that's the one that you would say would be the winner there's no way other other than that to really kind of fix this problem so anyways that is really all we need to do here like that that is it for this program so the last thing i'm going to do is i am going to print out in kind of a nicer way what the winning turtle is so i'm going to say the winner is the turtle with color colon then comma and i will say winner so that's all we'll do so now we just have a nicer kind of output message saying this was the winning turtle and then i'm gonna say time dot sleep and i'm gonna sleep for five seconds just so that we have a few seconds to actually see which turtle was the winner before we just go ahead and close the program so hopefully that's clear but yeah that's really all we need so let's run this let's go with 10 turtles this time and let's see what we get let's just enjoy the turtle racing show okay so they're going to race you're going to notice the more turtles you have kind of the slower they go just because we have to move every single turtle one at a time we can't move like a bunch of turtles you know like the more chills we have the more we have to move into the longer it takes to run that's what i'm trying to say but we saw that the winner is the turtle with color green let's run this one more time with two turtles and you'll see that it goes like way faster because it's just these two guys that need to move purple was the winner and then if we kind of go back into cmd it says the winner is the turtle with color purple awesome so i think that's really all i need to show you here now all of this code will be available to download from the description in case you got lost or something that's not working but hopefully i did a good job at explaining a lot of these concepts hopefully you guys kind of learned how you can lay out a i don't want to say large but medium sized python program that has more than just a few lines of code and you get the idea behind these functions right so now at this point if i want to go change something like say i want to change the width of my screen since i use this width variable everywhere in my program and everything i did was very dynamic right i had like height over two i had width over two if i change the width up here now everything will just work right like if i change this to 700 and i change the height to 600 doesn't even have to be square let's just run the program again let's go with six racers and it's still going to be evenly spaced out on the screen right just because the way we did this is everything was dynamic it used the variables and we set it up in a way where if we made any changes later on it wouldn't completely ruin or mess up our program and what does it say the winner is here the winner is turtle with color blue so just keep that in mind hopefully you appreciate that kind of detail in writing this code and same thing here even with like validating the input right we're gonna keep asking the user for a valid input until they give us something that's valid and then race uh we're using another function inside of this function we could have just took take uh took and taken whatever all of this code and placed it inside of here but if we did that then if we wanted to change the way that we were creating our turtles well we could do that but it would just be a little bit harder and if we wanted to say use this function anywhere else same thing just wouldn't work as well so this way it's really easy to see laid out very nicely and this is just a better style of coding than writing everything in one line right because we could have written this entire program in just one line like we didn't have to use any functions it could have just all been in the main line of the program but then it wouldn't be very clear to see what part of the program was doing what awesome so i hope you guys enjoyed if you did make sure to leave a like that's really all i have for you today so subscribe to the channel and i will see you guys in another youtube video you
Info
Channel: Tech With Tim
Views: 29,289
Rating: undefined out of 5
Keywords: tech with tim, python, python tutorial, python program, python for beginners, beginner python tuorial, tutorial for python, how to code in python, how to code, coding tutorial, beginner coding, beginner coding tutorial, turtle racing in python, beginner python tutorial, basic python tutorial, simple python program, how to make a python program, python program example, python program tutorial, basic python program, learning python for beginners, turtle module python
Id: gQP0geNsO4A
Channel Id: undefined
Length: 55min 36sec (3336 seconds)
Published: Sat Mar 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.