Open In App

Build epic PyGame -Skiing Adventure

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to make a skier game in Pygame. In this game, a skier character skins on a snowy slope while avoiding obstacles and collecting flags to score points. The skier can move left and right to navigate the slope and must avoid colliding with trees and stones.

Modules Required

  1. ‘sys: This module provides access to some variables used or maintained by the interpreter and to functions that interact with the interpreter.
  2. ‘cfg’: This module contains configuration settings and file paths for the game.
  3. ‘pygame’: This is the main module of the PyGame library, used for creating the game and handling graphics, events, and sound.
  4. ‘random’: This module is used for generating random numbers used in the game.
  5. ‘os’: module provides a portable way of using operating system-dependent functionality.

There are some trees and stones as obstacles and flags to increase the score and the speed of the skier increases for every 100 points.

  • Scoring of the game: when he collects flags coming his way he scores 10 points.
  • losingloses points: when he gets collides with trees he loses 5 points, and then got hit by stones he loses 10 points.

A scoreboard will display the score and when the score reaches less than “0” the player is out and a dialog box appears to “Quit” or “Restart” the game. ( check out the video at the end)

Introduction to the code

We will be using PyGame(a Python library) to create this Skier game. PyGame is an open-source library that is designed for making video games. it helps us to create fully functional games and multimedia programs in Python.

File Structure

This is how your repository structure should look in the end after walking through the entire article.

skier-game-file-structure
skier game file structure

Download the necessary images, font, and music from here resources.

Full Code:

FULL SOURCE CODE : GitHub Link (click here)

Stepwise Implementation and Functionality:

Step 1:  Represents the skier character in the game, allowing movement, turning, and handling collisions with obstacles.

The ‘SkierClass’ represents the skier character in the game. The __init__ method initializes the skier’s attributes, such as ‘direction’, ‘imagepaths’, ‘image’, ‘rect’, ‘speed’, ‘flag_count’, and ‘score’. The ‘turn’ method allows the skier to change direction by updating the ‘direction’ attribute and loading the appropriate skier image. The ‘move’ method updates the skier’s position by moving it horizontally based on the current speed. The ‘setFall’ method sets the skier’s image to a falling image when the skier hits an obstacle (tree or stone). The ‘setForward’ method sets the skier’s image to a forward image after the skier recovers from a fall.

Python3




import sys
  
import cfg
import pygame
import random
import os
  
class SkierClass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        # Initialize the skier's attributes
        self.direction = 0 
        # Paths to skier's images for different directions
        self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]  
         # Load the skier's image
        self.image = pygame.image.load(self.imagepaths[self.direction]) 
        self.rect = self.image.get_rect()  
         # Set the initial position of the skier
        self.rect.center = [320, 100
        # Skier's speed (x, y)
        self.speed = [self.direction, 6 - abs(self.direction) * 2]  
        self.flag_count = 0  
        self.score = 0 
  
    def turn(self, num):
        self.direction += num
        # Limit the direction to -2 (left) as minimum
        self.direction = max(-2, self.direction) 
        # Limit the direction to 2 (right) as maximum
        self.direction = min(2, self.direction)  
        center = self.rect.center
        self.image = pygame.image.load(self.imagepaths[self.direction]) 
        self.rect = self.image.get_rect() 
        self.rect.center = center
         # Update the skier's speed based on the new direction
        self.speed = [self.direction, 6 - abs(self.direction) * 2
        return self.speed
  
    def move(self):
        self.rect.centerx += self.speed[0]
        self.rect.centerx = max(20, self.rect.centerx) 
        # Limit the skier's position to the left edge of the screen
        self.rect.centerx = min(620, self.rect.centerx)  
        # Limit the skier's position to the right edge of the screen
  
    def setFall(self):
        # Set the skier's image to the falling image when the skier hits an obstacle (tree or stone)
        self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
  
    def setForward(self):
        # Set the skier's image to the forward image after the skier recovers from a fall
        self.direction = 0 
        self.image = pygame.image.load(self.imagepaths[self.direction])
  
  
# The code continues with other classes and functions


Step 2: Represents individual obstacles in the game and collision detection.

This class represents an individual obstacle in the game

  • __init__(self, img_path, location, attribute): The constructor method initializes the attributes of the obstacle object. It takes the image path, location coordinates, and attributes as parameters. It sets the image, location, rectangle, attribute, and passed status of the obstacle.
  • move(self, num): This method updates the vertical position of the obstacle by subtracting the given value `num` from its y-coordinate.

Python3




class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self, img_path, location, attribute):
        pygame.sprite.Sprite.__init__(self)
        # Set attributes for the obstacle
        self.img_path = img_path
        self.image = pygame.image.load(self.img_path)
        self.location = location  
        self.rect = self.image.get_rect()  
        self.rect.center = self.location 
        # A string representing the type of obstacle (e.g., "tree", "stone", or "flag")
        self.attribute = attribute 
        self.passed = False 
    def move(self, num):
        # Move the obstacle upwards by subtracting 'num' from its y-coordinate
        self.rect.centery = self.location[1] - num  


Step 3: Creating Obstacles

This function creates a group of obstacles based on the given parameters.

  • s: The starting row index for generating random obstacle positions.
  • e: The ending row index for generating random obstacle positions.
  • num‘: The number of obstacles to create (default value is 10).

The function generates random locations for the obstacles within the specified row range. The obstacles can be trees or stones, which are distributed based on the value of `i` modulo 4. The obstacle’s image path, location, and attribute are set accordingly. An instance of the ObstacleClass is created for each obstacle and added to the ‘obstacles’ group. Finally, the function returns the group of obstacles.

Python3




def createObstacles(s, e, num=10):
  # Create an empty sprite group to store the obstacles
    obstacles = pygame.sprite.Group()  
    locations = [] 
    for i in range(num):
        # Generate random row and column indices within the specified range
        row = random.randint(s, e)
        col = random.randint(0, 9)
  
        # Calculate the obstacle's location based on the row and column indices
        location = [col * 64 + 20, row * 64 + 20]
  
          
        if location not in locations:
            locations.append(location)  # Add the location to the list to avoid duplicates
            # Distribute trees
            if i % 4 == 0:
                attribute = "tree"  
            # Distribute stones
            elif i % 4 == 1:
                attribute = "stone"
            # Distribute flags
            else:
                attribute = "flag"
  
            # Get the image path corresponding to the attribute from the config module
            img_path = cfg.OBSTACLE_PATHS[attribute]
  
            # Create an obstacle instance with the determined attribute and add it to the group
            obstacle = ObstacleClass(img_path, location, attribute)
            obstacles.add(obstacle)
  
    return obstacles 


Step 4: Combines two sets of obstacles into one group

  • obstacles0: The first set of obstacles to combine.
  • obstacles1: The second set of obstacles to combine.

Python3




def AddObstacles(obstacles0, obstacles1):
   # Create an empty sprite group to store the combined obstacles
    obstacles = pygame.sprite.Group()  
  
    # Add all obstacles from obstacles0 to the combined group
    for obstacle in obstacles0:
        obstacles.add(obstacle)
  
    # Add all obstacles from obstacles1 to the combined group
    for obstacle in obstacles1:
        obstacles.add(obstacle)
  
    return obstacles  


Step 5: Displays the player’s score on the screen

This function displays the score on the screen. It creates a font object using ‘pygame.font.Font‘ with a specified font path and size. The rendered score text is then blitted onto the screen at the specified position using ‘screen.blit’.

Python3




def showScore(screen, score, pos=(10, 10)):
    font = pygame.font.Font(cfg.FONTPATH, 30)
    score_text = font.render("Score: %s" % score, True, (0, 0, 0))
    screen.blit(score_text, pos)


Step 6: Shows the game’s start interface with instructions.

This function displays the start interface of the game.

Rect objects are obtained for the title and content text using ‘get_rect()‘.The positions of the title and content text are set using ‘trect.midtop’ and ‘crect.midtop’, respectively. The rendered title and content text are then blitted onto the screen at their respective rect positions using ‘screen.blit’.If a key press event occurs, the function returns, indicating that the start interface should be closed.

Python3




def ShowStartInterface(screen, screensize):
    #white color
    screen.fill((255, 255, 255))  
    #title font
    tfont = pygame.font.Font(cfg.FONTPATH, screensize[0] // 5
    #content font
    cfont = pygame.font.Font(cfg.FONTPATH, screensize[0] // 20)
    #red color
    title = tfont.render(u'Skier Game', True, (255, 0, 0))
    # Content text in blue color
    content = cfont.render(u'Press any key to START.', True, (0, 0, 255))  
  
    trect = title.get_rect()  
    # Set the position of the title text at the top center
    trect.midtop = (screensize[0] / 2, screensize[1] / 5)  
    crect = content.get_rect()  
    crect.midtop = (screensize[0] / 2, screensize[1] / 2)  
    # Blit (draw) the title text onto the screen at the specified position
    screen.blit(title, trect)  
    screen.blit(content, crect)
  
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
               # Exit the function and start the game when any key is pressed
                return 
  
        pygame.display.update() 


Step 7: Updates and displays the game frame on the screen

This function updates the game frame on the screen.

The obstacles are drawn on the screen using ‘obstacles.draw(screen)’.The skier’s image is blitted onto the screen at its current position using ‘screen.blit(skier.image, skier.rect)’.The score is displayed on the screen by calling showScore(screen, skier.score).

Python3




def updateFrame(screen, obstacles, skier):
    screen.fill((255, 255, 255))
    obstacles.draw(screen)
    screen.blit(skier.image, skier.rect)
    showScore(screen, skier.score)
    pygame.display.update()


Step 8: Main function

1. Game Initialization:

Initializes the Pygame library, mixers for sound, and loads the background music.Sets the volume and plays the background music.Creates the game window with a specific size using pygame.display.set_mode() and sets the window caption.

2. Start Interface and Game Loop:

Calls the ShowStartInterface() function to display the start interface and waits for a key press event to start the game.Enters the main game loop, which continues until the game is restarted or quit.

3. Game Initialization and Loop:

Initializes the necessary game objects, such as the skier and obstacles.Checks for key press events to restart the game or quit.Updates the skier’s position and the distance traveled. Updates the frame by calling updateFrame() to display the obstacles and the skier.Controls the game’s frame rate using clock.tick(cfg.FPS).

4. Game Termination

Breaks out of the main game loop if the game should quit.Exits the program if the game window is closed.

Python3




def main():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
  
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('Skier Game')
  
    ShowStartInterface(screen, cfg.SCREENSIZE)
  
    while True:
        skier = SkierClass()
        # Decrease number of trees and stones
        obstacles0 = createObstacles(20, 29, num=15
        obstacles1 = createObstacles(10, 19, num=15)  
        obstaclesflag = 0
        obstacles = AddObstacles(obstacles0, obstacles1)
        clock = pygame.time.Clock()
        distance = 0
        # Variable to track whether the game should restart or quit
        restart = False 
  
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                        skier.turn(-1)
                    elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                        skier.turn(1)
                    # Press 'q' to quit the game
                    elif event.key == pygame.K_q:  
                        pygame.quit()
                        sys.exit()
                    # Press 'r' to restart the game
                    elif event.key == pygame.K_r:  
                        restart = True
            # Exit the inner loop to restart the game
            if restart:
                break  
  
            skier.move()
            distance += skier.speed[1]
            if distance >= 640 and obstaclesflag == 0:
                obstaclesflag = 1
                # Decrease number of trees and stones
                obstacles0 = createObstacles(20, 29, num=15)  
                obstacles = AddObstacles(obstacles0, obstacles1)
  
            if distance >= 1280 and obstaclesflag == 1:
                obstaclesflag = 0
                distance -= 1280
                for obstacle in obstacles0:
                    obstacle.location[1] = obstacle.location[1] - 1280
                # Decrease number of trees and stones
                obstacles1 = createObstacles(10, 19, num=15)  
                obstacles = AddObstacles(obstacles0, obstacles1)
  
            for obstacle in obstacles:
                obstacle.move(distance)
  
            hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)
            if hitted_obstacles:
                if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:
                    # Decrease score by 5 when hitting a tree
                    skier.score -= 5  
                    skier.setFall()
                    # Decrease skier's speed
                    skier.speed[1] = 2  
                    updateFrame(screen, obstacles, skier)
                    pygame.time.delay(1000)
                    skier.setForward()
                    # Reset skier's speed
                    skier.speed[1] = 6  
                    hitted_obstacles[0].passed = True
                elif hitted_obstacles[0].attribute == "stone" and not hitted_obstacles[0].passed:
                    # Decrease score by 10 when hitting a stone
                    skier.score -= 10  
                    skier.setFall()
                    # Decrease skier's speed
                    skier.speed[1] = 2  
                    updateFrame(screen, obstacles, skier)
                    pygame.time.delay(1000)
                    skier.setForward()
                    # Reset skier's speed
                    skier.speed[1] = 6  
                    hitted_obstacles[0].passed = True
                elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:
                    # Increase score by 10 when collecting a flag
                    skier.score += 10  
                    skier.flag_count += 1
                    # Increase speed after collecting 10 flags
                    if skier.flag_count >= 10:  
                        skier.speed[1] = 8
                    obstacles.remove(hitted_obstacles[0])
  
            updateFrame(screen, obstacles, skier)
            if skier.score < 0:  
                # Check if score is negative
                screen.fill((255, 255, 255))
                font = pygame.font.Font(cfg.FONTPATH, 40)
                game_over_text = font.render("Game Over", True, (255, 0, 0))
                prompt_text = font.render("Press 'r' to restart or 'q' to quit.", True, (0, 0, 255))
                game_over_rect = game_over_text.get_rect(center=(cfg.SCREENSIZE[0] // 2, cfg.SCREENSIZE[1] // 2))
                prompt_rect = prompt_text.get_rect(center=(cfg.SCREENSIZE[0] // 2, cfg.SCREENSIZE[1] // 2 + 50))
                screen.blit(game_over_text, game_over_rect)
                screen.blit(prompt_text, prompt_rect)
                pygame.display.update()
  
                while True:
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            sys.exit()
                        if event.type == pygame.KEYDOWN:
                           # Press 'r' to restart the game
                            if event.key == pygame.K_r: 
                                restart = True
                            # Press 'q' to quit the game
                            elif event.key == pygame.K_q:  
                                pygame.quit()
                                sys.exit()
                     # Exit the inner loop to restart the game
                    if restart:
                        break  
  
            clock.tick(cfg.FPS)
        # Exit the outer loop if the game should quit
        if not restart:
            break  
  
if __name__ == '__main__':
    main()


Combine all the steps code and put them in one file (Game.py)

Complete Code

In the below code have the full implementation of the game integrated in one code file involving the function of game functionality.

Python3




import sys
import cfg
import pygame
import random
import os
  
class SkierClass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        # Initialize the skier's attributes
        self.direction = 0
        # Paths to skier's images for different directions
        self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]
         # Load the skier's image
        self.image = pygame.image.load(self.imagepaths[self.direction])
        self.rect = self.image.get_rect()
         # Set the initial position of the skier
        self.rect.center = [320, 100]
        # Skier's speed (x, y)
        self.speed = [self.direction, 6 - abs(self.direction) * 2]
        self.flag_count = 0
        self.score = 0
  
    def turn(self, num):
        self.direction += num
        # Limit the direction to -2 (left) as minimum
        self.direction = max(-2, self.direction)
        # Limit the direction to 2 (right) as maximum
        self.direction = min(2, self.direction)
        center = self.rect.center
        self.image = pygame.image.load(self.imagepaths[self.direction])
        self.rect = self.image.get_rect()
        self.rect.center = center
         # Update the skier's speed based on the new direction
        self.speed = [self.direction, 6 - abs(self.direction) * 2]
        return self.speed
  
    def move(self):
        self.rect.centerx += self.speed[0]
        self.rect.centerx = max(20, self.rect.centerx)
        # Limit the skier's position to the left edge of the screen
        self.rect.centerx = min(620, self.rect.centerx)
        # Limit the skier's position to the right edge of the screen
  
    def setFall(self):
        # Set the skier's image to the falling image when the skier hits an obstacle (tree or stone)
        self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
  
    def setForward(self):
        # Set the skier's image to the forward image after the skier recovers from a fall
        self.direction = 0
        self.image = pygame.image.load(self.imagepaths[self.direction])
  
  
# The code continues with other classes and functions
  
class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self, img_path, location, attribute):
        pygame.sprite.Sprite.__init__(self)
        self.img_path = img_path
        self.image = pygame.image.load(self.img_path)
        self.location = location
        self.rect = self.image.get_rect()
        self.rect.center = self.location
        self.attribute = attribute
        self.passed = False
  
    def move(self, num):
        self.rect.centery = self.location[1] - num
  
  
def createObstacles(s, e, num=10):
    obstacles = pygame.sprite.Group()
    locations = []
    for i in range(num):
        row = random.randint(s, e)
        col = random.randint(0, 9)
        location = [col * 64 + 20, row * 64 + 20]
        if location not in locations:
            locations.append(location)
            if i % 4 == 0:
                attribute = "tree"  
                # Distribute trees
            elif i % 4 == 1:
                attribute = "stone"  
                # Distribute stones
            else:
                attribute = "flag"  
                # Distribute flags
            img_path = cfg.OBSTACLE_PATHS[attribute]
            obstacle = ObstacleClass(img_path, location, attribute)
            obstacles.add(obstacle)
    return obstacles
  
  
def AddObstacles(obstacles0, obstacles1):
    obstacles = pygame.sprite.Group()
    for obstacle in obstacles0:
        obstacles.add(obstacle)
    for obstacle in obstacles1:
        obstacles.add(obstacle)
    return obstacles
  
def showScore(screen, score, pos=(10, 10)):
    font = pygame.font.Font(cfg.FONTPATH, 30)
    score_text = font.render("Score: %s" % score, True, (0, 0, 0))
    screen.blit(score_text, pos)
  
  
def ShowStartInterface(screen, screensize):
    screen.fill((255, 255, 255))
    tfont = pygame.font.Font(cfg.FONTPATH, screensize[0] // 5)
    cfont = pygame.font.Font(cfg.FONTPATH, screensize[0] // 20)
    title = tfont.render(u'Skier Game', True, (255, 0, 0))
    content = cfont.render(u'Press any key to START.', True, (0, 0, 255))
    trect = title.get_rect()
    trect.midtop = (screensize[0] / 2, screensize[1] / 5)
    crect = content.get_rect()
    crect.midtop = (screensize[0] / 2, screensize[1] / 2)
    screen.blit(title, trect)
    screen.blit(content, crect)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                return
        pygame.display.update()
  
  
def updateFrame(screen, obstacles, skier):
    screen.fill((255, 255, 255))
    obstacles.draw(screen)
    screen.blit(skier.image, skier.rect)
    showScore(screen, skier.score)
    pygame.display.update()
  
  
def main():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
  
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('Skier Game')
  
    ShowStartInterface(screen, cfg.SCREENSIZE)
  
    while True:
        skier = SkierClass()
  
        obstacles0 = createObstacles(20, 29, num=15)  
        # Decrease number of trees and stones
        obstacles1 = createObstacles(10, 19, num=15
        # Decrease number of trees and stones
        obstaclesflag = 0
        obstacles = AddObstacles(obstacles0, obstacles1)
  
        clock = pygame.time.Clock()
  
        distance = 0
  
        restart = False 
        # Variable to track whether the game should restart or quit
  
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                        skier.turn(-1)
                    elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                        skier.turn(1)
                    elif event.key == pygame.K_q:  
                        # Press 'q' to quit the game
                        pygame.quit()
                        sys.exit()
                    elif event.key == pygame.K_r:  
                        # Press 'r' to restart the game
                        restart = True
  
            if restart:
                break  
                # Exit the inner loop to restart the game
  
            skier.move()
            distance += skier.speed[1]
            if distance >= 640 and obstaclesflag == 0:
                obstaclesflag = 1
                obstacles0 = createObstacles(20, 29, num=15)  
                # Decrease number of trees and stones
                obstacles = AddObstacles(obstacles0, obstacles1)
  
            if distance >= 1280 and obstaclesflag == 1:
                obstaclesflag = 0
                distance -= 1280
                for obstacle in obstacles0:
                    obstacle.location[1] = obstacle.location[1] - 1280
                obstacles1 = createObstacles(10, 19, num=15)  
                # Decrease number of trees and stones
                obstacles = AddObstacles(obstacles0, obstacles1)
  
            for obstacle in obstacles:
                obstacle.move(distance)
  
            hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)
            if hitted_obstacles:
                if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:
                    skier.score -= 5 
                    # Decrease score by 5 when hitting a tree
                    skier.setFall()
                    skier.speed[1] = 2 
                    # Decrease skier's speed
                    updateFrame(screen, obstacles, skier)
                    pygame.time.delay(1000)
                    skier.setForward()
                    skier.speed[1] = 6 
                    # Reset skier's speed
                    hitted_obstacles[0].passed = True
                elif hitted_obstacles[0].attribute == "stone" and not hitted_obstacles[0].passed:
                    skier.score -= 10  
                    # Decrease score by 10 when hitting a stone
                    skier.setFall()
                    skier.speed[1] = 2 
                    # Decrease skier's speed
                    updateFrame(screen, obstacles, skier)
                    pygame.time.delay(1000)
                    skier.setForward()
                    skier.speed[1] = 6 
                    # Reset skier's speed
                    hitted_obstacles[0].passed = True
                elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:
                    skier.score += 10  
                    # Increase score by 10 when collecting a flag
                    skier.flag_count += 1
                    if skier.flag_count >= 10:  
                        # Increase speed after collecting 10 flags
                        skier.speed[1] = 8
                    obstacles.remove(hitted_obstacles[0])
  
            updateFrame(screen, obstacles, skier)
            if skier.score < 0:  
                # Check if score is negative
                screen.fill((255, 255, 255))
                font = pygame.font.Font(cfg.FONTPATH, 40)
                game_over_text = font.render("Game Over", True, (255, 0, 0))
                prompt_text = font.render("Press 'r' to restart or 'q' to quit.", True, (0, 0, 255))
                game_over_rect = game_over_text.get_rect(center=(cfg.SCREENSIZE[0] // 2, cfg.SCREENSIZE[1] // 2))
                prompt_rect = prompt_text.get_rect(center=(cfg.SCREENSIZE[0] // 2, cfg.SCREENSIZE[1] // 2 + 50))
                screen.blit(game_over_text, game_over_rect)
                screen.blit(prompt_text, prompt_rect)
                pygame.display.update()
  
                while True:
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            sys.exit()
                        if event.type == pygame.KEYDOWN:
                            if event.key == pygame.K_r:  
                                # Press 'r' to restart the game
                                restart = True
                            elif event.key == pygame.K_q:  
                                # Press 'q' to quit the game
                                pygame.quit()
                                sys.exit()
  
                    if restart:
                        break 
                        # Exit the inner loop to restart the game
  
            clock.tick(cfg.FPS)
  
        if not restart:
            break  
            # Exit the outer loop if the game should quit
  
  
if __name__ == '__main__':
    main()


Other file: (cfg.py)

This file can be described as a configuration file for the game. It defines various constants and paths used in the game, such as the frame rate, screen size, paths to image and audio resources, and font path.

Python3




import os
FPS = 40 #The frame rate of the game, specifying how many frames should be displayed per second.
SCREENSIZE = (640, 640)
SKIER_IMAGE_PATHS = [
    os.path.join(os.getcwd(), 'resources/images/skier_forward.png'),
    os.path.join(os.getcwd(), 'resources/images/skier_right1.png'),
    os.path.join(os.getcwd(), 'resources/images/skier_right2.png'),
    os.path.join(os.getcwd(), 'resources/images/skier_left2.png'),
    os.path.join(os.getcwd(), 'resources/images/skier_left1.png'),
    os.path.join(os.getcwd(), 'resources/images/skier_fall.png')
]
  
OBSTACLE_PATHS = {
    'tree': os.path.join(os.getcwd(), 'resources/images/tree.png'),
    'flag': os.path.join(os.getcwd(), 'resources/images/flag.png'),
    'stone': os.path.join(os.getcwd(), 'resources/images/stone.png')
}
  
BGMPATH = os.path.join(os.getcwd(), 'resources/music/bgm.mp3')
# The path to the background music file used in the game.
FONTPATH = os.path.join(os.getcwd(), 'resources/font/FZSTK.TTF')
#The path to the font file used for text rendering in the game.


Terminal:
And finally, run the below command to start the game.

python Game.py

Output:

View the game here : Skiing Adventure



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads