Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
Resource icon

Simple pygame dodge car game - sprite collisions

In this part of the tutorial we will be adding sprite collision detection
In the game loop, I put it right under the update and draw

Python:
    '''
        Mob has moved off the screen kill
        the sprite. Create a new mob.
    '''
    if mob.rect.top > 720: # Screen height
            mob.kill() # Kill the sprite
            for i in range(3): # Create 3 new mobs and add to sprite group
                mob = Mob()
                mob.centerx = randint(510, 770)
                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)


And now our full code is looking some thing like this

Python:
# 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
        

    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


# 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)

# Set a loop variable
running = True

# Start the game loop
while running:

    # Set background color
    screen.fill('seagreen')

    '''
     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)


    
    # Update the screen
    pygame.display.update()

    # Set our framerate
    clock.tick(fps)
pygame.quit()

In the final tutorial we will add a start page and maybe a scoring system
Back
Top Bottom