In this article, you'll learn how to build a racing game in Python using the Turtle library in just 39 lines of code.
Here's what we're going to create:
š§µ Prerequisites
Very basic knowledge of Python programming will be enough to go through this tutorial. Also, I assume that you don't know anything about this turtle library. I will teach you everything from scratch.
š Tools we'll use
First, if you don't have Python installed on your machine, go to python.org to download the latest version of Python and then install it right away.
For writing the program, we will be using PyCharm, which is the most popular integrated development environment (IDE) for Python. After installing PyCharm on your machine, you are ready to build this amazing game from scratch.
ā³ Project Goals
Concretely, we'll write a program that moves a turtle object horizontally until it reaches our calculated finish line. š
Then we will create seven unique replicas of this turtle object using a for loop
along with different colors and random moving speeds.
We'll also add a background image (roads with lanes for the turtles to race in) to create something like a real racing environment.
Then we'll compute different values along the vertical or Y-axis to define their starting locations.
Finally, we will prompt the user to enter their bet (turtle color) so that if a user's bet color matches our winner's turtle color, we will display "Winner!" on the screen. Otherwise, we'll display "You Lost!" on the screen.
Note: For screen readers or anyone who is interested in getting the full source code of this project, you can access it in my GitHub Repository here.
So, are you excited to build this game? I'm too. Let's begin!
š©āš» How to Set Up the Project
Open your PyCharm IDE. Then click New Project.
Let's call itĀ racing-gameĀ and clickĀ create.
Then, add a new Python file calledĀ main.py
.
š How to Use the Turtle Library
Now, let's go toĀ turtle-graphics python documentation. Here you will find the full details about this library.
I recommend reading this documentation at least once before jumping into the code. But don't worry, I will simplify it for you while we're writing the program.
Import the Library
So let's importĀ TurtleĀ andĀ ScreenĀ from the turtle module.
Call this Screen in a new variable calledĀ screen. Then, call theĀ screen.exitonclick()
Ā function to stop the program when we click on the screen.
š£ļø Designing Game Canvas
Now, let's work with the screen object to define our game canvas.
So, let's set theĀ widthĀ to 800 pixels andĀ heightĀ to 600 pixels.
Here is the result:
š Adding Background Graphics
It's time to load our background image for our canvas. So let's drag ourĀ road.gifĀ file into our racing-game project.Ā
You can download this background image from here
Let's add this image usingĀ screen.bgpic
('road.gif')`.
Here is the result:
š¢ Working with Turtle Objects
Now, let's create a turtle instance using theĀ Turtle()
Ā method with the shape calledĀ turtle.
But it will seem really small. So we need defineĀ shapesize(2)
.
Turtle Location
Now we need to change our turtle's location to the left bottom corner usingĀ goto(x=-350, y=-260)
.
So here we setĀ x
Ā for moving the turtle horizontally andĀ y
Ā for vertically along with the computed values with respect to our canvas.
Here you can see that the turtle has moved to our desired location.
So, we can take theĀ y
Ā position in a global variable and add different types of values for positioning our turtles on their respective roads.
Turtle replicas
Now, we have to create seven different types of turtle objects. For this reason, we will use aĀ for loop
.
SoĀ for
Ā index inĀ range(0, 7)
Ā and then move our existing turtle instance in this loop. And of course, we have to changeĀ y
Ā to our globalĀ y
Ā positions variable and get theirĀ indexesĀ in order.
Here is the result:
Turtle color
So as you can see, we have seven turtle instances created equally with differentĀ y
Ā locations. Let's add some random colors by using a global colors variable as we did for theĀ y
Ā positions. Then use theĀ color(colors[index])
Ā method with their indexes.
Here is the result ā beautiful!
The ugly lines
You may see that there are some ugly lines that point towards the middle, and the move direction is very slow. So we can use theĀ speed('fastest')
Ā andĀ penup()
Ā methods to solve these problems. Have a look!
Move the turtles forward
Now, what else do we need? Yeah, you got it! We need to define a random pace for every turtle. But before doing that, how can we move a single turtle forward?
Well, you can use theĀ forward()
Ā method to do this.
Let's say we need to move our turtles forward 30 pixels.
Here is the result:
But they are not moving continuously. What else can we do here? Think about it and come back to see my solutions.
So, to solve this problem, we take a variable calledĀ is_onĀ and set it toĀ True
. Now we will continuously execute our program until we break it using aĀ while
Ā loop.
Now, we have the opportunity to move our turtle forward continuously with 30 pixels in every step.
Here is the result:
It's moving like a plane because we setĀ forward
Ā to 30. š¤£
For now, let's keep it like that. We will fix it after all turtles be able to run together and then adjust the speed accordingly.
Run multiple turtles in sync
Now we need to target all the turtle objects, not just a single one. But how can we do it? Think about it and come back to see my solution.
So, we can take a global variable calledĀ all_turtleĀ and set it to an empty list. Now, in the for loop, after creating seven new turtle instances, we canĀ append
Ā our new born turtle to this globalĀ all_turtleĀ list. This way we can access them in other code blocks.
Now we have all our turtles. So, while ourĀ is_on
Ā variable in true, we can sayĀ all_turtle.forward(10)
. Also, here we need to use a for loop
again to get each turtle from thisĀ all_turleĀ global variable and then move themĀ forward
Ā by 10 pixels.
Let's see the result up until now:
Setting random moving speed
So, we solved our turtle moving problem. But they're running infinitely ā there is no ending point.
Also all turtles are moving at the same speed. Think about this problem, and try to solve it on your own.
So let's take a new variableĀ random_paceĀ and set it toĀ random.randint(0, 7)
. It will return value between zero to seven randomly. You have to import random at the top. Finally pass thisĀ random_paceĀ variable to theĀ forward()
Ā method likeĀ forward(random_pace)
.
Here is the result:
š How to Set the Finish Line
Now, we need to define our finish line in this canvas. To solve this problem, we checkĀ if
Ā turtle.xcor()
Ā > 330, setĀ is_onĀ =Ā False
, else we need to continue executing our program.
šāāļø How to Prompt the User to Enter Their Bet
We are done with the UI. Now, we need to define some logic to let the user enter their bet and compare their bet with our programmed result.
To let the user enter their bet, we can writeĀ screen.textinput
Ā and with a placeholderĀ 'Enter your bet'. We'll alsoĀ prompt
Ā the userĀ "which turtle color"Ā and store it in a global variableĀ user_bet.
Then we take a variableĀ winner. We check ifĀ winner == user_bet
Ā which will come from the user's input color. We printĀ You Won, Otherwise,Ā You lostĀ with the turtle winner's color. That's why we have to use an f-string to pass the variable in the print method.
š How to Show the Results on the Screen
Now, I want you to show this print text in the canvas with their responsive turtle color after touching the finish line. How can you implement this? You will see my solution next.
So, here in the top. We take two global variablesĀ ALIGN = "right"
Ā andĀ FONT = ("Courier", 28, "bold")
. We will write to align the text on the right, and also make the font family courier and font size 28, bold.
Now, we'll use them when we want to show the user the racing results. So when the winner turtle color is equal to the user_bet color, we have to show the text in the canvas instead of printing it in the terminal.
To do this, we writeĀ turtle.write()
Ā and past the print statement along with font=FONTĀ and align=ALIGN. Else, we need to show the text "You lost" with the same variableĀ FONTĀ andĀ ALIGN. See, this is the benefit of using global variables.
Finally, let's run this code one more time. Let's say that the red turtle will be the winner. But, as you can see below ā Oops, the yellow turtle is the winner. So, you can see the bold yellow font displayed next to this turtle. This is why we used align = "right" and set the turtle color using theĀ turtle.pencolor()
Ā method.
And there you have it - we've built our turtle racing game. If you want to watch this tutorial in video form, here's a full video tutorial for you:
š¹ Full video tutorial: How to make racing game in python
š Conclusion
So, we are at the end of this racing game project. If you liked this article, feel free to follow me for daily programming news and productivity.
Read More: Why we need math in programming
Top comments (0)