Python game development, pygame module, python implementation of chemical skiing games

Previous review

Python implements "Bunny and Bun" game

Python implementation of eight tone symbol games

Python puzzle games

preface:

In this issue, we will make a simple skiing game.
No more nonsense. Let's start happily~

result

The old rule is that we should look at the renderings first

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.

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

'''Skiers'''
class SkierClass(pygame.sprite.Sprite):
	def __init__(self):
		pygame.sprite.Sprite.__init__(self)
		# Orientation of skiers (- 2 to 2)
		self.direction = 0
		self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]
		self.image = pygame.image.load(self.imagepaths[self.direction])
		self.rect = self.image.get_rect()
		self.rect.center = [320, 100]
		self.speed = [self.direction, 6-abs(self.direction)*2]
		'''Change the orientation of the skier. Negative numbers are left, positive numbers are right, and 0 is forward'''
	def turn(self, num):
		self.direction += num
		self.direction = max(-2, self.direction)
		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
		self.speed = [self.direction, 6-abs(self.direction)*2]
		return self.speed
	'''Mobile skier'''
	def move(self):
		self.rect.centerx += self.speed[0]
		self.rect.centerx = max(20, self.rect.centerx)
		self.rect.centerx = min(620, self.rect.centerx)
'''Obstacles'''
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
	'''move'''
	def move(self, num):
		self.rect.centery = self.location[1] - num

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:

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

Then we can define the main loop:

'''Game main loop'''
	while True:
		# --Event capture
		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:
					speed = skier.turn(-1)
				elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
					speed = skier.turn(1)
		'''--Update the data of the current game frame'''
		skier.move()
		distance += speed[1]
		if distance >= 640 and obstaclesflag == 0:
			obstaclesflag = 1
			obstacles0 = createObstacles(20, 29)
			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)
			obstacles = AddObstacles(obstacles0, obstacles1)
		for obstacle in obstacles:
			obstacle.move(distance)
		'''--collision detection '''
		hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)
		if hitted_obstacles:
			if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:
				score -= 50
				skier.setFall()
				updateFrame(screen, obstacles, skier, score)
				pygame.time.delay(1000)
				skier.setForward()
				speed = [0, 6]
				hitted_obstacles[0].passed = True
			elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:
				score += 10
				obstacles.remove(hitted_obstacles[0])
        '''--Update screen'''
		updateFrame(screen, obstacles, skier, score)
		clock.tick(cfg.FPS)

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:

'''Display the game start interface'''
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'Skiing game', True, (255, 0, 0))
	content = cfont.render(u'Press any key to start the game', 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()

This is the end of the article. Thank you for watching, Python 24 games series , the next article shares the classic 90 tank battle

In order to thank readers, I would like to share some of my recent collection of programming dry goods with you and give back to every reader. I hope I can help you.

Dry goods mainly include:

① More than 2000 Python e-books (both mainstream and classic books should be available)

② Python standard library materials (the most complete Chinese version)

③ Project source code (forty or fifty interesting and classic hand training projects and source code)

④ Videos on basic introduction to Python, crawler, web development and big data analysis (suitable for Xiaobai)

⑤ Python learning roadmap (bid farewell to non stream learning)

⑥ Two days of Python crawler training camp live rights

All done ~ like + comment ~ see personal profile or private letter for complete source code..

Keywords: Python Game Development pygame

Added by flappy_warbucks on Sun, 16 Jan 2022 23:34:08 +0200