Scoring:
- Create a function for displaying text
- Player class add attribute for keeping the score total
- Blit the score to the screen
def score(score):
# Create a font and size
font = pygame.font.Font(None, 35)
# Create the surface text anti-alias, color
surface = font.render(f'Score: {score}', True, 'green')
# Get the rect/size of screen and font surface
screen_rect = screen.get_rect()
surf_rect = surface.get_rect()
# Center will be screen center x cord - text width / 2
centerx = screen_rect.centerx - surf_rect.width / 2
# Blit to screen surface with tuple (centerx, 10pixel from top)
screen.blit(surface, (centerx, 10))
Player class add the attribute
self.score = 0
Blit the score to the screen
In the game loop add the function call
score(player.score)
In the section of the game loop that has the block
'''
Mob has moved off the screen kill
the sprite. Create a new mob.
'''
for mobs in mob_sprite:
if mobs.rect.top > 720:
mobs.kill()
player.score += 1 # Add this line
mob = Mob()
mob_sprite.add(mob)
Now for the start page
Create a class called StartPage and add this code block below the last class created
class StartPage:
def __init__(self):
waiting = True
screen.fill('seagreen')
while waiting:
font = pygame.font.Font(None, 85)
surface = font.render('Welcome to Dodge Car', True, (20,250,0))
center = screen.get_rect().centerx - (surface.get_rect().width/2)
screen.blit(surface, (center, 20))
font2 = pygame.font.Font(None, 48)
surf2 = font2.render('Press space to start - ESC to quit', True, 'yellow')
center2 = screen.get_rect().centerx - (surf2.get_rect().width/2)
screen.blit(surf2, (center2, screen.get_rect().centery))
# Poll pygame events
event = pygame.event.poll()
# Exit the game
if event.type == pygame.QUIT:
os.sys.exit()
# Check for key press
if event.type == pygame.KEYDOWN:
# If the key press is space - exit to game
if event.key == pygame.K_SPACE:
waiting = False
if event.key == pygame.K_ESCAPE:
os.sys.exit()
pygame.display.update()
clock.tick(fps)
Right before the game loop create a variable
gameover = True
Then after the while loop add
if gameover:
StartPage()
gameover = False
# Create the player, player sprite group and add player to sprite group
player = Player()
player_sprite = pygame.sprite.Group()
player_sprite.add(player)
The lines of code above the loop that are the same can be removed.
Now the full code should look like this
# Do the imports
import pygame
import os
from random import randint, randrange, choice
'''
Get the path of the working directory
Should get the correct path in console or editor
We will use this to access directories containing
images and sound
'''
path = os.path.realpath(os.path.dirname(__file__))
'''
Initiate pygame to acces all classes and functions
'''
pygame.init()
'''
Setup the pygame time clock.
We will use this to set the framerate
'''
clock = pygame.time.Clock()
# Set the framerate
fps = 60
'''
Setup our screen window. A tuple is needed for setting width and height
I'm going to use a 1280 width and 720 height
'''
screen_size = (1280, 720)
screen = pygame.display.set_mode(screen_size)
# Set the caption for the window
pygame.display.set_caption('Dodge Car')
# define a function to draw the yellow lines
def line(surf, x):
line = pygame.Surface((2, 720))
line.fill('yellow')
surf.blit(line, (x, 0))
# Define a function to draw the dotted white line
def line2(surf, x):
line = pygame.Surface((2, 20))
line.fill('white')
for i in range(720):
if i % 10 == 0:
surf.blit(line,(x, i*10))
# Define a function to draw the road
def road(screen):
surf = pygame.Surface((300, 720))
surf.fill('black')
screen.blit(surf, (490,0))
def score(score):
# Create a font and size
font = pygame.font.Font(None, 35)
# Create the surface text anti-alias, color
surface = font.render(f'Score: {score}', True, 'green')
# Get the rect/size of screen and font surface
screen_rect = screen.get_rect()
surf_rect = surface.get_rect()
# Center will be screen center x cord - text width / 2
centerx = screen_rect.centerx - surf_rect.width / 2
# Blit to screen surface with tuple (centerx, 10pixel from top)
screen.blit(surface, (centerx, 10))
# Create a class for playe car
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# Load image
self.image = pygame.image.load(f'{path}/media/images/cars/pixel_racecar_blue.png')
self.image = pygame.transform.scale(self.image, (30,40))
self.rect = self.image.get_rect()
self.rect.centerx = 645
self.rect.bottom = 700
self.speedx = 0
self.score = 0
def update(self):
'''
Method for updating sprite movement
'''
# Set the speed
self.speedx = 0
# Get keys pressed
keystate = pygame.key.get_pressed()
# If the left arrow or a key is pressed, player moves left
if keystate[pygame.K_LEFT] or keystate[pygame.K_a]:
self.speedx = -5
# If the right arrow or d key is pressed, go right
if keystate[pygame.K_RIGHT] or keystate[pygame.K_d]:
self.speedx = 5
# sprite speed
self.rect.x += self.speedx
# Set boundries for movement. We don't want to go off road
if self.rect.left < 495:
self.rect.left = 495
if self.rect.right > 785:
self.rect.right = 785
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# Get a list of cars from the image directory
cars = os.listdir(f'{path}/media/images/cars')
# This can be commented out to use all cars.
# Using it to not have a mob with the same as a player car
mobcars = [car for car in cars if car != 'pixel_racecar_blue.png']
# Load a random image using choice from pyhton random module
self.image = pygame.image.load(f'{path}/media/images/cars/{choice(mobcars)}')
# Scale the image and rotate so the car is facing player
self.image = pygame.transform.scale(self.image, (30,40))
self.image = pygame.transform.rotate(self.image, 180)
# Get the rect for the image
self.rect = self.image.get_rect()
# Creating a random center for the mob so as to have them
# start at a random place instead of all at the same place
self.rect.centerx = randint(510, 770)
# They will start off the screen view
self.rect.bottom = -50
# Set a random speed
self.speedy = randint(7,10)
def update(self):
# Method updates mob movement
# Give and update the speed
self.rect.y += self.speedy
class StartPage:
def __init__(self):
waiting = True
screen.fill('seagreen')
while waiting:
font = pygame.font.Font(None, 85)
surface = font.render('Welcome to Dodge Car', True, (20,250,0))
center = screen.get_rect().centerx - (surface.get_rect().width/2)
screen.blit(surface, (center, 20))
font2 = pygame.font.Font(None, 48)
surf2 = font2.render('Press space to start - ESC to quit', True, 'yellow')
center2 = screen.get_rect().centerx - (surf2.get_rect().width/2)
screen.blit(surf2, (center2, screen.get_rect().centery))
# Poll pygame events
event = pygame.event.poll()
# Exit the game
if event.type == pygame.QUIT:
os.sys.exit()
# Check for key press
if event.type == pygame.KEYDOWN:
# If the key press is space - exit to game
if event.key == pygame.K_SPACE:
waiting = False
if event.key == pygame.K_ESCAPE:
os.sys.exit()
pygame.display.update()
clock.tick(fps)
# Set a loop variable
running = True
# Set a gameover variable
gameover = True
# Start the game loop
while running:
# Set background color
screen.fill('seagreen')
if gameover:
StartPage()
gameover = False
# Create the player, player sprite group and add player to sprite group
player = Player()
player_sprite = pygame.sprite.Group()
player_sprite.add(player)
# Create a mob, mob sprite group, and add mob to sprite_group
mob_sprite = pygame.sprite.Group()
for i in range(3):
mob = Mob()
mob_sprite.add(mob)
'''
Get pygame events. There is 2 ways to do this.
We can use pygame.event.poll() - return one event or
we can use a loop and get all events. We will use the latter -
pygame.event.get()
'''
# Get keys that are pressed
key = pygame.key.get_pressed()
for event in pygame.event.get():
# A way to exit pygame
if event.type == pygame.QUIT:
running = False
# Can press the esc key and exit the game
if key[pygame.K_ESCAPE]:
running = False
# Blit the road
road(screen)
line(screen, 493)
line(screen, 785)
line2(screen, 640)
# Update and draw sprites
player_sprite.update()
player_sprite.draw(screen)
mob_sprite.update()
mob_sprite.draw(screen)
'''
Mob has moved off the screen kill
the sprite. Create a new mob.
'''
for mobs in mob_sprite:
if mobs.rect.top > 720:
mobs.kill()
player.score += 1
mob = Mob()
mob_sprite.add(mob)
# Detect collisions # player sprite, mob sprite - kill both
collision = pygame.sprite.groupcollide(player_sprite, mob_sprite, True, True)
for crash in collision: # Loop through the variable checking for sprite collisions
# Create new player and mobs
player = Player()
player_sprite.add(player)
mob = Mob()
mob.centerx = randint(510, 770)
mob_sprite.add(mob)
# Print player score to screen
score(player.score)
# Update the screen
pygame.display.update()
# Set our framerate
clock.tick(fps)
pygame.quit()
You can add multiple images such as the picture below where I've added trees.
You can bullets and many other things such as sound effects and music.
This concludes the tutorial. Thanks and have fun coding.....