Write games in python: add ending settings to "Alien Invasion"

Project requirements:

In the game Alien Invasion, the player controls a spaceship that initially appears at the bottom center of the screen. Players can use the arrow keys to move the spaceship left and right, and the space bar to shoot. The game starts with a group of aliens appearing in the sky and they move down the screen. The player's task is to shoot and kill these aliens. After the player wipes out all the aliens, a new group of aliens will appear, and the speed at which they move. Whenever an alien hits the player's ship or reaches the bottom of the screen, the player loses a ship. The game ends after the player loses three ships.

In the first phase, we created a spaceship that can move left and right and fire when the user presses the space bar. With this behavior in place, we were able to turn our attention to the aliens and improve the gameplay of the game.

Past Blogs
About: Blog about setting up your spaceship

About: Adding shooting function to the spaceship blog

In the previous chapter, we added the alien crowd and set up the processing of bullets hitting the aliens.

About: Setting Up Alien Crowd Blog


The content of this chapter is as follows:

End Game

When the player fails to destroy the invading aliens within the agreed time, or the aliens reach the edge of the screen, or the aliens hit the spaceship, destroying all the life of the spaceship, then the game is over, and the player can only proceed by restarting the game new game.

Detecting Alien and Spaceship Collisions

First check for collisions between the alien and the spaceship so that the alien can respond if it hits the spaceship.
Detect collisions between aliens and spaceships immediately after updating each alien's position.

game_functions.py:

def update_aliens(ai_settings,ship,aliens):
	#检查是否有外星人位于屏幕边缘,并更新整群外星人的位置
	check_fleet_edges(ai_settings,aliens)
	
	#更新外新人群中所有外星人的位置
	aliens.update()
	
	if pygame.sprite.spritecollideany(ship,aliens):
		print("Ship hit!!!")

method spritecollideany:

This method accepts two parameters, a sprite and a marshal.
It checks to see if any member of the group collides with the sprite, and stops traversing the group when it finds a member that collides with the sprite. Returns None if no collision occurred. But if there is an alien colliding with the spacecraft, return to the elves in the formation, that is, the aliens.

When aliens and spaceships collide, there are many tasks to be performed:

All remaining aliens and bullets need to be deleted, the spaceship re-centered, and a swarm of aliens created. Before writing the code to accomplish these tasks, it is necessary to determine whether a collision detection method for aliens and spaceships is feasible. And the easiest way to determine this is to write a print statement.

Responding to Alien and Spaceship Collisions

Here, we need to determine what to do when the alien collides with the spaceship.

Instead of destroying the ship and recreating the ship,
keep track of how many times the ship has been hit by tracking game stats (tracking stats help keep score).

GameStats class for statistical game information:

game_stats.py:

class GameStats():
	#跟踪游戏的统计信息
	def __init__(self,ai_settings):
		self.ai_settings = ai_settings
		self.rest_stats()
	
	def rest_stats(self):
		#初始化在游戏运行期间可能变化的统计信息
		self.ships_left = self.ai_settings.ship_limit

In the GameStats class, we define the statistical information of the tracking game. In the init method, the information is not directly initialized, but the rest_stats method defined below is called to initialize the information.

The values ​​stored in the ships_left variable are:

settings.py:

#飞船的生命值
self.ship_limit = 3

Now that we have our stats class for tracking game information, we need to make a change to alien_invasion.py
as we are importing the newly created class in this main file.

alien_invasion.py:

from game_stats import GameStats

def run_game():
	#创建一个用于存储游戏统计信息的实例
	stats = GameStats(ai_settings)

	
	# while 循环来控制游戏
	while True:
		gf.update_aliens(ai_settings,stats,screen,ship,aliens,bullets)
		


We imported a new class: GameStats, the purpose of which is to create instances of it, use the parameter passed by update_aliens() to keep track of how many ships the player has left , and to create a new group of aliens Star.

Now, when the alien hits the spaceship, we subtract 1 from the remaining spaceships, create a new group of aliens, and reposition the spaceship to the bottom center of the screen. Oh yes! Don't forget to pause the game for a while, because the player needs to be aware of the collision before the new alien swarm appears.
game_functions:

from time import sleep

def ship_hit(ai_settings,stats,screen,ship,aliens,bullets):
	#响应外星人撞到的飞船
	stats.ships_left -= 1
	
	#清空外星人列表和子弹列表
	aliens.empty()
	bullets.empty()
	
	#创建一群新的外星人,并将飞船放到屏幕底部中央
	create_fleet(ai_settings,screen,ship,aliens)
	ship.center_ship()
	
	#暂停
	sleep(0.5)

def update_aliens(ai_settings,stats,screen,ship,aliens,bullets):
	#检查是否有外星人位于屏幕边缘,并更新整群外星人的位置
	check_fleet_edges(ai_settings,aliens)
	
	#更新外新人群中所有外星人的位置
	aliens.update()
	
	if pygame.sprite.spritecollideany(ship,aliens):
		#print("Ship hit!!!")
		ship_hit(ai_settings,stats,screen,ship,aliens,bullets)

Import the function sleep() in the time module to pause the game.
The new function ship_hit responds when the ship is hit by an alien. Inside the entire function, decrement the number of remaining spaceships by 1, then clear the group of aliens and bullets. The spaceship and aliens are dealt with and the game is paused.

ship.py:

	def center_ship(self):
		self.center = self.screen_rect.centerx

In order to make the spaceship return to the center of the screen after being hit, the center_ship method is defined. Set the spaceship's attribute center to the x-coordinate of the center of the screen, which is obtained through the attribute screen_rect.

There are aliens reaching the bottom of the screen

If an alien reaches the bottom of the screen, we'll respond as if an alien had crashed into a spaceship.

Add a function that performs this task and call it check_aliens_bottom():

game_functions.py

def check_aliens_bottom(ai_settings,stats,screen,ship,aliens,bullets):
	#检查是否有外星人到达底部
	screen_rect = screen.get_rect()
	
	for alien in aliens.sprites():
		if alien.rect.bottom >= ship.rect.bottom:
			ship_hit(ai_settings,stats,screen,ship,aliens,bullets)
			break

Check to see if any aliens have reached the bottom of the screen, and if so, call the ship_hit method to place the ship in the center of the screen. The detection condition is to compare the bottom value of the spacecraft and the alien. If the value of the alien is greater than the value of the spacecraft, it means that the alien has reached the bottom.

The new method defined above is called after updating the positions of all aliens and checking if the aliens have collided with the spaceship:

def update_aliens(ai_settings,stats,screen,ship,aliens,bullets):
	check_aliens_bottom(ai_settings,stats,screen,ship,aliens,bulltets)
game over

Below we define a flag to end the game after the player's ship runs out of health:

game_stats.py:

		#将该标志定义在 init 方法当中
		#在游戏刚启动时处于活动状态
		self.game_active = True
	

When the life value of the spaceship controlled by the player is 0, we set it to False.

game_functions.py:

def ship_hit(ai_settings,stats,screen,ship,aliens,bullets):
	if stats.ships_left > 0:
		#响应外星人撞到的飞船
		stats.ships_left = -1
	
		#清空外星人列表和子弹列表
		aliens.empty()
		bullets.empty()
	
		#创建一群新的外星人,并将飞船放到屏幕底部中央
		create_fleet(ai_settings,screen,ship,aliens)
		ship.center_ship()
		#暂停
		sleep(0.5)
	else:
		stats.game_active = False
Determine which parts of the game should run
# while 循环来控制游戏
	while True:
		gf.check_events(ai_settings,screen,ship,bullets)
		if stats.game_active:
			ship.update()
			gf.update_bullets(ai_settings,screen,ship,aliens,bullets)
			gf.update_aliens(ai_settings,stats,screen,ship,aliens,bullets)
		
		bullets.update()
		gf.update_screen(ai_settings,screen,ship,aliens,bullets)

Guess you like

Origin blog.csdn.net/tianlei_/article/details/129942059