Fun Create Car Game with Pygame

Fiko Aditama
4 min readJun 5, 2023

--

Pygame is a library or module in the Python programming language that is used for game development. It provides various features and functions that enable game developers to easily create games using Python. With Pygame, developers can access and control various aspects of the game, including graphics, sound, user input, and more. Pygame also supports game development using sprites, collision detection, animation, and more. It is a popular choice for developing both simple 2D games and more complex ones using Python.

This time, I will try to create a simple Car Game using Python.

Here is code,

import pygame 
from pygame.locals import *
import random

pygame.init()

# create the window
width, height = 500, 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Car Game')

# colors
gray = (100, 100, 100)
green = (76, 208, 56)
red = (200, 0, 0)
white = (255, 255, 255)
yellow = (255, 232, 0)

# game settings
gameover = False
speed = 2
score = 0


# markers size
marker_width = 10
marker_height = 50

# read and edge markers
road = (100, 0, 300, height)
left_edge_marker = (95, 0, marker_width, height)
right_edge_marker = (395, 0, marker_width, width)

# x coordinates of Lanes
left_lane = 150
center_lane = 250
right_lane = 350
bottom_lane = height - marker_height
top_lane = 0
lanes = [left_lane, center_lane, right_lane]

# for animating movement of the Lane markers
lane_marker_move_y = 0


class Vehicle(pygame.sprite.Sprite):
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)

# scale the image down to it fits in the lane
image_scale = 45 / image.get_rect().width
new_width = image.get_rect().width * image_scale
new_height = image.get_rect().height * image_scale
self.image = pygame.transform.scale(image, (new_width, new_height))

self.rect = self.image.get_rect()
self.rect.center = [x, y]

class PlayerVehicle(Vehicle):
def __init__(self, x, y):
image = pygame.image.load('car.png')
super().__init__(image, x, y)

# player's starting coordinates
player_x = 250
player_y = 400

player_group = pygame.sprite.Group()
player = PlayerVehicle(player_x, player_y)
player_group.add(player)

image_filenames = ['enemy.png', 'car.png', 'car.png']
vehicle_images = []
for image_filename in image_filenames:
image = pygame.image.load(image_filename)
vehicle_images.append(image)

vehicle_group = pygame.sprite.Group()

# Load the crash image
crash = pygame.image.load('car.png')
crash_rect = crash.get_rect()


# game loop
clock = pygame.time.Clock()
fps = 120
running = True

while running:
clock.tick(fps)

for event in pygame.event.get():
if event.type == QUIT:
running = False

# move the player's car using left/right arrow keys
elif event.type == pygame.KEYDOWN:
if event.key == K_LEFT and player.rect.center[0] > left_lane:
player.rect.x -= 100
elif event.key == K_RIGHT and player.rect.center[0] < right_lane:
player.rect.x += 100
elif event.key == K_UP and player.rect.center[1] > top_lane:
player.rect.y -= 100
elif event.key == K_DOWN and player.rect.center[1] < bottom_lane:
player.rect.y += 100

# check if there's a side swipe collision after changing lane
for vehicle in vehicle_group:
if pygame.sprite.collide_rect(player, vehicle):
gameover = True

# place the player's car next to other vehicle
# and determine where to position the crash image
if event.key == K_LEFT:
player.rect.left = vehicle.rect.right
crash_rect.center = [player.rect.left, (player.rect.center[1] + vehicle.rect.center[1])/2]
elif event.key == K_RIGHT:
player.rect.right = vehicle.rect.left
crash_rect.center = [player.rect.right, (player.rect.center[1] + vehicle.rect.center[1])/2]

elif event.type == pygame.MOUSEMOTION:
pass
elif event.type == pygame.MOUSEBUTTONUP:
pass
elif event.type == pygame.MOUSEBUTTONDOWN:
pass
elif event.type == pygame.KEYUP:
pass
elif event.type == pygame.ACTIVEEVENT:
pass

# draw the grass
screen.fill(green)

# draw the road
pygame.draw.rect(screen, gray, road)

# draw the edge markers
pygame.draw.rect(screen, yellow, left_edge_marker)
pygame.draw.rect(screen, yellow, right_edge_marker)

# draw the Lane markers
lane_marker_move_y += speed * 2
if lane_marker_move_y >= marker_height * 2:
lane_marker_move_y = 0
for y in range(marker_height * -2, height, marker_height * 2):
pygame.draw.rect(screen, white, (left_lane + 45, y + lane_marker_move_y, marker_width, marker_height))
pygame.draw.rect(screen, white, (center_lane + 45, y + lane_marker_move_y, marker_width, marker_height))


# draw the player's car
player_group.draw(screen)

# add vr to two vehicles
if len(vehicle_group) < 2:
# ensure there's enough gap between vehicles
add_vehicle = True
for vehicle in vehicle_group:
if vehicle.rect.top < vehicle.rect.height * 1.5:
add_vehicle = False
if add_vehicle:
# select a random lane
lane = random.choice(lanes)
# select a random vehicle image
image = random.choice(vehicle_images)
vehicle = Vehicle(image, lane, height / -2)
vehicle_group.add(vehicle)

# make the vehicles move
for vehicle in vehicle_group:
vehicle.rect.y += speed

# remote the vehicle once it goes off screen
if vehicle.rect.top >= height:
vehicle.kill()

# add to score
score+=1

if score > 0 and score % 5 == 0:
speed+=1
# draw the vehicles
vehicle_group.draw(screen)

# display the score
font = pygame.font.Font(pygame.font.get_default_font(), 16)
text = font.render('Score ' + str(score), True, white)
text_rect = text.get_rect()
text_rect.center = (50, 450)
screen.blit(text, text_rect)

# check if there's a head an collision
if pygame.sprite.spritecollide(player, vehicle_group, True):
gameover = True
crash_rect.center = [player.rect.center[0], player.rect.top]

# display game over
if gameover:
screen.blit(crash, crash_rect)
pygame.draw.rect(screen, red, (0, 50, width, 100))
font = pygame.font.Font(pygame.font.get_default_font(), 16)
text = font.render('Game over, Play again? ( Enter Y or N', True, white)
text_rect = text.get_rect()
text_rect.center = (width / 2, 100)
screen.blit(text, text_rect)

while gameover:
clock.tick(fps)
for event in pygame.event.get():
if event.type == QUIT:
gameover = False
running = False

# get the player's input ( y or n)
if event.type == KEYDOWN:
if event.type == K_y:
gameover = False
speed = 2
score = 0
vehicle_group.empty()
player.rect.center = [player_x, player_y]
elif event.key == K_n:
# check the loops
gameover = False
running = False


pygame.display.update()
pygame.display.flip()

pygame.quit()

insipration -> https://www.youtube.com/watch?v=XDM6UmnMCDE

From the code above, you can try to modify and customize it according to your preferences. Thank you.

--

--

Fiko Aditama
Fiko Aditama

No responses yet