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 👇👇
Python version: 3.6.4
And some Python built-in modules.
Install Python and add it to the environment variable. pip can install the relevant modules required.
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:
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.
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): pygame.sprite.Sprite.__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 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): pygame.sprite.Sprite.__init__(self) 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 # 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): locations.append(location) type = random.choice(["tree","flag"]) if type == "tree": img = "skier_tree.png" elif type == "flag": img = "skier_flag.png" obstacle = ObstacleClass(img,location,type) obstacles.add(obstacle) # Create a window with trees and flags def animate(): screen.fill([255,255,255]) obstacles.draw(screen) screen.blit(skier.image,skier.rect) screen.blit(score_text,[10,10]) pygame.display.flip() # Redraw the picture pygame.init() 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 create_map() 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 # Scroll scene if map_position >= 640 : create_map() map_position = 0 # Create a new scene hit = pygame.sprite.spritecollide(skier,obstacles,False) if hit: if hit.type == "tree" and not hit.passed: points -=100 skier.image = pygame.image.load("skier_crash.png") score_text = font.render("Score:" +str(points),1,(0,0,0)) pygame.time.delay(100) skier.iamge = pygame.image.load("skier_down.png") skier.angle = 0 speed = [0,6] hit.passed = True elif hit.type == "flag" and not hit.passed: points +=10 hit.kill() # Detect whether it touches trees or small flags obstacles.update() score_text = font.render("Score:" +str(points),1,(0,0,0)) # Show score animate() pygame.quit()
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 💪💪