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 - Player and Mobs

In this tutorial we will be creating a classes for the player and mob cars
In the cars images I downloaded, I took and edited the images with gimp as the has space around them that was causing the mob cars to hit
the player car at a distance. I just used crop to shrink/remove the spaces.

I've hard coded the placements and boundries for the cars and mobs for the tutorial. There are other ways to
get placement and boundries.

I used pygame.sprite.Sprite functionality for detecting collisions

First the player class
Python:
# 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

Now the mob class
Python:
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(6,9)

    def update(self):
        # Method updates mob movement

        # Give and update the speed
        self.rect.y += self.speedy


Now the car.py should be looking something like this.
[B]Note:[/B] I have created and added a player, player sprite group, and added the player to the sprite group

[CODE=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))


# 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(randrange(3, 4)):
    mob = Mob()
    mob.rect.centerx = randint(510, 770)
    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)
  
    # Update the screen
    pygame.display.update()
    # Set our framerate
    clock.tick(fps)
pygame.quit()

Our screen should look like this and the player car should be able to move to the left and right
using either the a and d keys or the left and right arrow keys.
  • Kazam_screenshot_00000.png
    Kazam_screenshot_00000.png
    7.8 KB · Views: 67
Back
Top Bottom