current position:Home>Python game development, pyGame module, python implementation of skiing games

Python game development, pyGame module, python implementation of skiing games

2021-08-23 02:47:49 Chu_ Yang

Preface :

In this issue, we will make a simple skiing game .
I don't say much nonsense , Let's start happily ~

result

As a rule, let's take a look at the renderings first

image.png

development tool

Python edition :3.6.4

Related modules :

pygame modular ;

As well as some Python Built in modules .

Environment building

install Python And add to environment variable ,pip Install the relevant modules required .

Principle introduction

The rules of the game :

Players go through “AD” Key or “←→” Control the skier on the move , Try to avoid the trees on the road , Try to pick up the little flag on the road .

If you hit a tree , Then the score is reduced 50, If you find a flag , Then the score will be increased 10.

Step by step :

Step1: Define the sprite class

Because the game involves collision detection ( The skier's collision with trees and flags ), So we define two elf classes , Used to represent skiers and obstacles respectively ( Trees and flags ):

''' Skiers '''
class SkierClass(pygame.sprite.Sprite):
	def __init__(self):
		pygame.sprite.Sprite.__init__(self)
		#  The direction of the skier (-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 direction of the skier .  Negative numbers are left , A positive number is right ,0 To move 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 skiers '''
	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 , Skiers should have left in their progress , The ability to shift to the right , And it makes sense that the skier's forward speed should slow down during the offset , Only in this way can players operate . meanwhile , Skiers should have different postures to show how they are sliding :

A straight line :

 picture

A little bit to the left :

 picture

A lot to the left :

 picture

A little bit to the right :

 picture

A lot to the right :

 picture

in addition , Although the left and right movements of skiers are achieved by moving the skiers themselves , But the skier moves forward by moving obstacles .

Step2: Create obstacles randomly

Now we need to define a function that randomly creates obstacles , So that it can be called in the main loop of the game :

image.png

The purpose of creating obstacles twice is to facilitate the screen connection .

Then we can define the main loop :

''' The main cycle of the game '''
	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 loop consists of :

Event monitoring 、 Update of obstacles 、 Collision detection and score display, etc , In short, it is easy to achieve .

Step4: other

Start 、 End the interface , It's up to us to play by ourselves , I just wrote a simple start interface :

''' Show 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 games ', 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 , Thanks for watching ,Python24 A series of small games , The next article shares the classics 90 Tanks war

To thank readers , I want to share with you some of my recent collections of programming dry goods , Give back to every reader , I hope I can help you .

Dry goods mainly include :

① 2000 Multiple copies Python e-book ( There should be both mainstream and classic books )

② Python Standard library information ( The most complete Chinese version )

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

④ Python Basic introduction 、 Reptiles 、web Development 、 Big data analysis video ( Suitable for Xiaobai to learn )

⑤ Python Learning Roadmap ( Farewell to bad learning )

All done~ give the thumbs-up + Comment on ~ See personal profile or private letter for complete source code ..

copyright notice
author[Chu_ Yang],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210823024746031a.html

Random recommended