Welcome back to a new tutorial series! In this series, we’ll go over making a car racing game in Python. We’ll be using one of my favorite modules, Pygame.
💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it out and get a discount on the platform using the code “techwithtim”
📄 Resources 📄
Download Image Assets:
Code In This Video:
Learn Python OOP:
Fix Pip (Mac):
Fix Pip (Windows):
📚 Playlist:
⭐️ Timestamps ⭐️
00:00 | Game Information and Demo
03:02 | Setup and Pygame Installation
06:00 | Loading Images/Assets
08:01 | Creating the Pygame Windows
10:19 | Displaying Images
15:45 | Resizing Images
21:20 | Rotating The Car
34:35 | Key Presses and Turning
36:28 | Acceleration and Velocity
40:21 | Moving The Car By An Angle
47:28 | Slowing Down The Car
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
💰 Courses & Merch 💰
💻 The Fundamentals of Programming w/ Python:
👕 Merchandise:
🔗 Social Medias 🔗
📸 Instagram:
📱 Twitter:
⭐ Discord:
📝 LinkedIn:
🌎 Website:
📂 GitHub:
🔊 Podcast:
🎬 My YouTube Gear 🎬
🎥 Main Camera (EOS Canon 90D):
🎥 Secondary Camera (Panasonic Lumix G7):
📹 Main Lens (EFS 24mm f/2.8):
🕹 Tripod:
🎤 Main Microphone (Rode NT1):
🎤 Secondary Microphone (Synco Wireless Lapel System):
🎤 Third Microphone (Rode NTG4+):
☀️ Lights:
⌨ Keyboard (Daskeyboard 4Q):
🖱 Mouse (Logitech MX Master):
📸 Webcam (Logitech 1080p Pro):
📢 Speaker (Beats Pill):
🎧 Headphones (Bose Quiet Comfort 35):
🌞 Lamp (BenQ E-reading Lamp):
🌞 Secondary Lamp (BenQ Screenbar Plus):
💻 Monitor (BenQ EX2780Q):
💻 Monitor (LG Ultrawide 34WN750):
🎙 Mic Boom Arm (Rode PSA 1):
🎚 Audio Interface (Focusrite Scarlet 4i4):
💸 Donations 💸
💵 One-Time Donations:
💰 Patreon:
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
⭐️ Tags ⭐️
– Tech With Tim
– Pygame
– Displaying Images
– Acceleration
– Velocity
– Algoexpert
⭐️ Hashtags ⭐️
#TechWithTim #PythonGame
johnnie gilkerson
08.07.2023Hi Tim, can't do pygame in vscode:
"pygame" is not accessedPylance
Import "pygame" could not be resolvedPylancereportMissingImports
Do you have any suggestions?
thanks
Candel Gaming
07.07.2023so hardworking boy😨❤️❤️❤️❤️
Nick Chourchoulis
07.07.202343:00: θ is a greek letter pog
ET Teo
07.07.2023Great tutorial. Took a while to understand that rotated image center. Got it! Thanks
Xenko Vence
07.07.2023Finally, a pygame tutorial that teaches you how to realistically use it. I can't tell you how long I've been looking for one of these. So many of the pygame tutorials out there just show you what you CAN do but never expand on HOW to actually use it, especially not in a real world environment.
Mehthab
07.07.2023Can this also be made in replit pygame?
Aarjav Jain
07.07.2023Hey Tim what’s your color scheme it looks amazing!
Mike D
07.07.2023Is anyone else unable to download the assets. I click the link it opens a new tab immediately closes and nothing is downloaded.
Also went direct to the the site to manually find it but it does appear to be on there.
mikyjet06
07.07.2023What's the matter with the nerds in the trigonometry section 🙂
Agent RR-007
07.07.2023This is awesome. I think you have explained it quite right.
balquist
07.07.2023i don't understand why vertical = math.cos(radians) * self.vel.
isn't it supposed to be sin? as y/r * r = y.
do yill
06.07.2023how do i make it so the top of my window is orange like at 18:45
Omar Ahmad
06.07.2023Love it Tim your the best coder on youtube thanks for doing it really appreciate it
Санчез Решает
06.07.2023Dear Tim, please make tutorial for pygame on Russian Language. You are talking too high speed and it so hard for undestand me
Green_Irishman
06.07.2023Didn't realize I was going to get a good Kahn Academy math less in trig with my awesome PyGame tutorial! Thanks Tim! (what was up with the nerds photo-bombing your paint window though?)
Fish bin Laden
06.07.2023The link to the assets opens and then closes immediately.
Atlatl Leader
06.07.2023Do you know about the pymunk module
razzzerblade _
06.07.2023can anybody repost a link to the image assets?
Wil Helm
06.07.2023Thank you very much for posting this!
DrFrost
06.07.2023i can't download the resources like the image, i mean i cant even go to the site the youtube just
Humzah Nouman
06.07.2023Hey Tim,
I am using a chromebook and when I try clicking on the same img link it isn't loading.
I tryed copy and pating in new browser but it's just plain white.
Is it because I am using Chrom OS?
J2frosty gaming
05.07.2023very nice and clear turorial!
PersiusKane ( Phoenix Studio )
05.07.2023It's fun to watch when he talks about trigonometry "A NERDS CANDY" banner sneaks in to the frames. 🙂
caleb meng GG
05.07.2023bang di gua layarnya kebesaran bang
Tchavo Frund
05.07.2023Hi Tim,
I'm facing a problem with the "pygame.time.clock()" and then "clock.tick(FPS)" lines as it says "pygame.time has no attribute clock" (so the window open but doesn't stay on the screen). I looked up on the internet and tried with the line "time.perf_counter() and time.process_time()", but still not working as I don't know what to then use instead of the "clock.tick(FPS)" line.
Hope you can help me!
And keep doing what you're doing, those are amazing tutorials!! Thanks
Pravachan patra
05.07.202335:25
Killian Ward
05.07.2023I can't download the assets, when I click the link in the description, it just opens an untitled tab that closes after a second without downloading anything
Lord English
05.07.2023Anyone else getting changes on audio? It switches between him sounding "normal" to sounding like he is talking into a tin can.
Tech Kid
05.07.2023Hi tim
I have an error that says: No file 'imgs/grass.jpg' found in working directory.
What can I do?
Justin S
05.07.2023this little car project kicked my butt lol
Amay Shukla
05.07.2023it is showing error in line 15 but i have written the same code that you have written
elektron2kim
04.07.2023Seriously. It's complicated and demanding to rotate an image. Why not make 36 images or so and save all that computation. Your game is not that pretty or anything. In "IrfanView" one can rotate by degrees. With 8 directions it's simplistic and some languages can rotate sprites just fine.
Nathu Lal
04.07.202328:28 whoever understood this is a legend
Nathu Lal
04.07.202343:45 i am so bad at maths
dieme kalombo
04.07.2023On the line of code that says:
blit_rotate_center(win, self.img, (self.x, self.y), self.angle)
There was an error that said:
blit_rotate_center() takes 3 positional arguments but 4 were given.
Can someone help me out?
Vid Pirnat - Slics Agency
04.07.2023hello tim pls help nice video btw
X Error of failed request: BadValue (integer parameter out of range for operation)
what do i do?
Poylman
04.07.2023Goat
IcyJack54
04.07.2023Respect boy. You‘re a boy with talent
paul ubakanma
04.07.2023I FOUND IT INTERSTING, THANKS FOR YOUR UPLOAD AND LECTURING, GOD BLESS
Boolean0_0
04.07.2023Congrats on one mil subscribers
Antonio García
04.07.2023This is what Im looking for, thanks so much Tim!
I will let here my modifications adding basic Drifting and Second player using arrows, if somebody need it…
Im using VS Code on Raspberry pi 4 with Raspbian bullseye, just change the path of assets.
import pygame
import time
import math
from utils import scale_image, blit_rotate_center
GRASS = scale_image(pygame.image.load("/home/tony/Desktop/Pygame-Car-Racer-main/tutorial1-code/imgs/grass.jpg"), 2.5)
TRACK = scale_image(pygame.image.load("/home/tony/Desktop/Pygame-Car-Racer-main/tutorial1-code/imgs/track.png"), 0.9)
TRACK_BORDER = scale_image(pygame.image.load("/home/tony/Desktop/Pygame-Car-Racer-main/tutorial1-code/imgs/track-border.png"), 0.9)
RED_CAR = scale_image(pygame.image.load("/home/tony/Desktop/Pygame-Car-Racer-main/tutorial1-code/imgs/red-car.png"), 0.55)
GREEN_CAR = scale_image(pygame.image.load("/home/tony/Desktop/Pygame-Car-Racer-main/tutorial1-code/imgs/green-car.png"), 0.55)
WIDTH, HEIGHT = TRACK.get_width(), TRACK.get_height()
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Racing Game!")
FPS = 60
class AbstractCar:
def __init__(self, max_vel, rotation_vel, velocity_momentum):
self.img = self.IMG
self.max_vel = max_vel
self.vel = 0
self.rotation_vel = rotation_vel
self.angle = 0
self.x, self.y = self.START_POS
self.acceleration = 0.1
self.momentum_direction = 0
self.velocity_momentum = velocity_momentum
def rotate(self, left=False, right=False, ninguno=False):
if left:
self.angle += self.rotation_vel
self.momentum_direction += self.velocity_momentum
elif right:
self.angle -= self.rotation_vel
self.momentum_direction -= self.velocity_momentum
elif ninguno:
diferencia = self.momentum_direction – self.angle
if diferencia > 0:
self.momentum_direction -= self.velocity_momentum/1.65
elif diferencia < 0:
self.momentum_direction += self.velocity_momentum/1.65
def draw(self, win):
blit_rotate_center(win, self.img, (self.x, self.y), self.angle)
def move_forward(self):
self.vel = min(self.vel + self.acceleration, self.max_vel)
self.move()
def move(self):
radians = math.radians(self.momentum_direction)
vertical = math.cos(radians) * self.vel
horizontal = math.sin(radians) * self.vel
self.y -= vertical
self.x -= horizontal
def reduce_speed(self):
self.vel = max(self.vel – self.acceleration / 2, 0)
self.move()
class PlayerCar(AbstractCar):
IMG = RED_CAR
START_POS = (180, 200)
class PlayerCar2(AbstractCar):
IMG = GREEN_CAR
START_POS = (160, 200)
def draw(win, images, player_car, player_car2):
for img, pos in images:
win.blit(img, pos)
player_car.draw(win)
player_car2.draw(win)
pygame.display.update()
run = True
clock = pygame.time.Clock()
images = [(GRASS, (0, 0)), (TRACK, (0, 0))]
player_car = PlayerCar(6, 6, 3)
player_car2 = PlayerCar2(6, 6, 3)
while run:
clock.tick(FPS)
draw(WIN, images, player_car, player_car2)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
keys = pygame.key.get_pressed()
moved = False
moved2 = False
if keys[pygame.K_a]:
player_car.rotate(left=True)
if keys[pygame.K_d]:
player_car.rotate(right=True)
if keys[pygame.K_d] & keys[pygame.K_a] == False:
player_car.rotate(ninguno=True)
if keys[pygame.K_w]:
moved = True
player_car.move_forward()
if not moved:
player_car.reduce_speed()
if keys[pygame.K_LEFT]:
player_car2.rotate(left=True)
if keys[pygame.K_RIGHT]:
player_car2.rotate(right=True)
if keys[pygame.K_LEFT] & keys[pygame.K_RIGHT] == False:
player_car2.rotate(ninguno=True)
if keys[pygame.K_UP]:
moved2 = True
player_car2.move_forward()
if not moved2:
player_car2.reduce_speed()
pygame.quit()
The Origami Knight
03.07.2023Thank you for this tutorial. I was looking for movement in a direction and you are the only one who has helped me.
Tyra Shorts
03.07.2023Sup tim would be nice if you could send me a pygame program that creats a dodge car game i already know the latter so don't stress yourself with the below:
Creating screen
Displaying image
Creating scrolling road
* By the way i am a beginner so all help will be much appreciated
JRC
03.07.2023Hi .. i am new to python .. can you help me by some solution .. from your code
i need position value of car how can i get this
swesty.
03.07.2023for anyone else does the grass code line not work
Binyameen Pehlari
03.07.2023anyoneknows why the class was created in the way it was. I mean why specific variables were defined as class attributes and specific variables were taken in innit. Is there any reason in particular for that, is there something we should keep in mind while defining class attributes and innit arguments ??
Chance Justine Bragais
03.07.2023So i have a problem in this part 31:21 ,I always get the Unresolved attribute reference 'IMG' for class 'AbstractCar also for the START_POS. Also in the def draw(win, images), I got this Shadows name 'images' from outer scope . I tried using chatgpt to find whats wrong, it give me a code where i put super. in class PlayerCar, and after that, it doesnt show anything. Please help me, I'm stuck here and I still don't know what to change.
tushal jain
03.07.2023hey tim i need your help in my car racing porject game please send me your emial id or something wos that i can contact you i really need an urgent hel of yours please provide me your contact please reply to the comment urgently need your help
Braiden Crow
03.07.2023"dont worry abt inheritance" continues to give a basic description of inheritance lol
Thestickbuster
03.07.2023thx tim