[collection of games] make a skiing game with Python ~ it's very suitable for fishing at work.

Posted by JohnnyBlaze on Wed, 05 Jan 2022 03:37:34 +0100


Hello, iron juice, a few days ago, it was snowing heavily in many cities ~ (Xiaobian in Hunan really didn't get too excited to see such heavy snow after a few years) I don't know if the lucky youyoumeng had fun snow? The snowball fight and the snowman wo are all played~ 😜😜

Skiing didn't come true, so this issue of Xiaobian wants to give you a skiing game. Let's start happily 👇👇

If you want to get more complete source code and python learning materials, you can send me a private letter or click this line of font


development tool

Python version: 3.6.4

Related modules:

pygame module;

And some Python built-in modules.

Environment construction

Install Python and add it to the environment variable. pip can install the relevant modules required.

Game Preview:

Principle introduction

Rules of the game:

Players use the "AD" key or "←→" to control the skiers moving forward, try to avoid the trees on the road and try to pick up the small flag on the road.

If you touch a tree, the score will be reduced by 50. If you pick up a small flag, the score will be increased by 10.

Step by step:

Step 1: define sprite class

Since the game involves collision detection (collision between skiers and trees and flags), we define two elf classes to represent skiers and obstacles (i.e. trees and flags):

Among them, the skier should have the ability to shift left and right in the process of moving forward, and it is more reasonable for the skier to slow down when shifting, so as to be operated by the player. At the same time, skiers should have different postures to express their sliding state:

Straight line:

A little to the left:

A lot to the left:

A little to the right:

A lot to the right:

In addition, although the left and right movement of the skier is realized by moving the skier itself, the forward movement of the skier is realized by moving an obstacle.

Step 2: create obstacles randomly

Now we need to define a function that randomly creates obstacles to invoke in the main game loop:

Step 3: game main loop

First, we initialize some parameters:

The purpose of creating obstacles twice is to facilitate picture connection.

Then we can define the main loop:

The main cycle includes:

Event monitoring, obstacle update, collision detection and score display are easy to implement.

Step4: others

The start and end interfaces are up to you. I wrote a simple start interface:


Attached source code:

import pygame,sys,random

skier_images= ["skier_down.png","skier_right1.png","skier_right2.png","skier_left1.png","skier_left2.png"]

class SkierClass(pygame.sprite.Sprite):

    def __init__(self):


        self.image = pygame.image.load("skier_down.png")

        self.rect = self.image.get_rect()

        self.rect.center = [320,100]

        self.angle = 0

        # Create a skier


    def turn(self,direction):

        self.angle = self.angle + direction

        if self.angle < -2 :

            self.angle = -2

        if self.angle > 2 :

            self.angle = 2

        center = self.rect.center

       self.image = pygame.image.load(skier_images[self.angle])

        self.rect = self.image.get_rect()

        self.rect.center = center

        speed = [self.angle , 6-abs(self.angle) * 2]

        return speed

        # Skier turning method

    def move(self,speed):

        self.rect.centerx = self.rect.centerx + speed[0]

        if self.rect.centerx <20 :

            self.rect.centerx = 20

        if self.rect.centerx >620:

            self.rect.centerx = 620

        # Skier movement method

class ObstacleClass(pygame.sprite.Sprite):

    def __init__(self,image_file,location,type):


        self.image_file = image_file

        self.image = pygame.image.load(image_file)

        self.rect = self.image.get_rect()

        self.rect.center = location

        self.type = type

        self.passed = False

        # Create trees and flags

    def update(self):

        global speed

        self.rect.centery -= speed[1] # The screen scrolls up

        if self.rect.centery <-32:

            self.kill() # Remove obstacles rolling down from the top of the screen

def create_map():

    global obstacles

    locations = []

    for i in range(10):

        row = random.randint(0,9)

        col = random.randint(0,9)

        location = [col *64 +20,row*64+20+640]

        if not (location in locations):


            type = random.choice(["tree","flag"])

            if type == "tree":

                img = "skier_tree.png"

            elif type == "flag":

                img = "skier_flag.png"

            obstacle = ObstacleClass(img,location,type)


    # Create a window with trees and flags

def animate():






    # Redraw the picture


screen = pygame.display.set_mode([640,640])

clock = pygame.time.Clock()

skier = SkierClass()

speed = [0,6]

obstacles = pygame.sprite.Group()

map_position = 0

points = 0


font = pygame.font.Font(None,50)

# Preparation screen

running = True

while running: # Main cycle

    clock.tick(30) # Graphics are updated 30 times per second

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:

                speed = skier.turn(-1)

            elif event.key == pygame.K_RIGHT:

                speed = skier.turn(1)

        # Retrieve user input

    skier.move(speed) # Mobile skier

    map_position += speed[1] # Scroll scene

    if map_position >= 640 :


        map_position = 0

        # Create a new scene

    hit = pygame.sprite.spritecollide(skier,obstacles,False)

    if hit:

        if hit[0].type == "tree" and not hit[0].passed:

            points -=100

            skier.image = pygame.image.load("skier_crash.png")

            score_text = font.render("Score:" +str(points),1,(0,0,0))


            skier.iamge = pygame.image.load("skier_down.png")

            skier.angle = 0

            speed = [0,6]

            hit[0].passed = True

        elif hit[0].type == "flag" and not hit[0].passed:

            points +=10


        # Detect whether it touches trees or small flags


    score_text = font.render("Score:" +str(points),1,(0,0,0)) # Show score



Execution effect:


That's the end of this little skiing game. Remember the third time in a row! The support of family members is the biggest driving force for Xiaobian to update 💪💪

Topics: Python Back-end Programmer