From python practice to introduction, self practice of exercises in Chapter 12 of alien project

Posted by ferrit91 on Fri, 22 Nov 2019 20:49:56 +0100

Similar to the expansion of the first part of the alien project:


At the beginning of self-study python, the alien project 12 chapters, completed a spacecraft can move left and right on the screen, and can fire. Because the following exercises are separate, in order to be simple, we just scrape them together and ignore some details. Then synthesize several exercises to complete the rocket's up, down, left and right movements. On this basis, it is assumed that the rocket fires at the right end. Of course, to fire in other directions, you only need to change the corresponding position.

1. The main program file exercise_test.py (similar to alien project's alien_investment. Py)

import sys
import pygame
from pygame.sprite import Group
import game_functions as gf
from settings import Settings
from rocket import Rocket


def run_game():
	
	#Initialize background settings
	pygame.init()
	#Create a display window called screen
	ai_settings = Settings()
	screen = pygame.display.set_mode((ai_settings.screen_width,
		ai_settings.screen_height))
	
	pygame.display.set_caption("Blue Sky")
	
	#Create a rocket
	rocket = Rocket(ai_settings, screen)
	
	#Create a group to store bullets
	bullets = Group()
	while True:
		gf.check_events(ai_settings, screen, rocket, bullets)
		rocket.update()
		gf.update_bullets(bullets, ai_settings)

		gf.update_screen(ai_settings, screen, rocket, bullets)
		

run_game()

2,game_function.py

import sys
import pygame
from bullet import Bullet

def check_keydown_events(event, ai_settings, screen, rocket, bullets):
	"""Response button"""
	if event.key == pygame.K_RIGHT:
		rocket.moving_right = True
	elif event.key == pygame.K_LEFT:
		rocket.moving_left = True
	elif event.key == pygame.K_UP:
		rocket.moving_up = True
	elif event.key == pygame.K_DOWN:
		rocket.moving_down = True
	elif event.key == pygame.K_SPACE:
		#Create a bullet and add it to the group bullets
		if len(bullets) < ai_settings.bullets_allowed:
			new_bullet = Bullet(ai_settings, screen, rocket)
			bullets.add(new_bullet)
		
def check_keyup_events(event, rocket):
	"""Response loosening"""
	if event.key == pygame.K_RIGHT:
		rocket.moving_right = False
	elif event.key == pygame.K_LEFT:
		rocket.moving_left = False
	elif event.key == pygame.K_UP:
		rocket.moving_up = False
	elif event.key == pygame.K_DOWN:
		rocket.moving_down = False

def check_events(ai_settings, screen, rocket, bullets):
	"""Respond to cases and mouse events"""
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
		elif event.type == pygame.KEYDOWN:
			check_keydown_events(event, ai_settings,screen, 
				rocket, bullets)
				
		elif event.type == pygame.KEYUP:
			check_keyup_events(event, rocket)
				
def update_screen(ai_settings, screen, rocket, bullets):
	"""Update the image on the screen and switch to the new screen"""
	#Redraw the screen every time you cycle
	screen.fill(ai_settings.bg_color)
	#Redraw all bullets behind rockets and aliens
	for bullet in bullets.sprites():
		bullet.draw_bullet()
	rocket.blitme()
		
	#Make the most recently drawn screen visible
	pygame.display.flip()

def update_bullets(bullets, ai_settings):
	"""Update the location of bullets and delete the disappeared bullets"""
	bullets.update()
	#Delete the disappeared bullets. Use the right border of the bullets to set it not to exceed the screen width
	for bullet in bullets.copy():
		if bullet.rect.right >= ai_settings.screen_width:
			bullets.remove(bullet)
	#Success can be detected by the following code
	"""print(len(bullets))"""

3,rocket.py

import pygame

class Rocket():
	def __init__(self, ai_settings, screen):
		#Initialize the rocket and set its initial position
		self.screen = screen
		self.ai_settings = ai_settings
		#Loading rocket image and obtaining its external rectangle
		self.image = pygame.image.load('images/rocket.bmp')
		self.rect = self.image.get_rect()
		self.screen_rect = screen.get_rect()
		
		#Put each rocket in the center of the screen
		self.rect.centerx = self.screen_rect.centerx
		self.rect.centery = self.screen_rect.centery
		
		#Store small values in the spaceship's attribute center
		self.center = float(self.rect.centerx)
		self.center_up_down = float(self.rect.centery)

		#Mobile logo
		self.moving_right = False
		self.moving_left = False
		self.moving_up = False
		self.moving_down = False
	def update(self):
		"""Adjust the position of the rocket according to the moving sign,Right left upper and lower"""
		if self.moving_right and self.rect.right < self.screen_rect.right:
			self.center += self.ai_settings.rocket_speed_factor
		if self.moving_left and self.rect.left > 0:
			self.center -= self.ai_settings.rocket_speed_factor
		if self.moving_up and self.rect.top > 0:
			self.center_up_down -= self.ai_settings.rocket_speed_factor
		if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
			self.center_up_down += self.ai_settings.rocket_speed_factor
			
		#Update rect object according to self.center
		self.rect.centerx = self.center
		self.rect.centery = self.center_up_down

	def blitme(self):
		"""Draw the rocket at the specified position"""
		self.screen.blit(self.image, self.rect)

4,setting.py

class Settings():
	"""Create a class with all settings"""
	
	def __init__(self):
		self.screen_width = 800
		self.screen_height = 600
		self.bg_color = (0, 191, 255)
		
		#Set the speed of the ship
		self.rocket_speed_factor = 1.5
		#Bullet setting
		self.bullet_speed_factor = 1
		self.bullet_width = 15
		self.bullet_height = 3
		self.bullet_color = 60, 60, 60
		self.bullets_allowed = 3

5,bullet.py

import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
	"""A class that manages the bullets fired by a spaceship"""
	
	def __init__(self, ai_settings, screen, rocket):
		"""Create a bullet object at the ship's location"""
		super().__init__()
		self.screen = screen
		
		#Create a rectangle representing the bullet at (0, 0) and set the correct position
		self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
		self.rect.centerx = rocket.rect.centerx
		self.rect.centery = rocket.rect.centery
		
		#Stores the bullet position as a decimal point
		self.y = float(self.rect.y)
		self.x = float(self.rect.x)
		
		self.color = ai_settings.bullet_color
		self.speed_factor = ai_settings.bullet_speed_factor
		
	def update(self):
		"""Moving bullets to"""
		#Update the small value indicating the bullet position, and determine the direction of the bullet by changing x and y
		self.x += self.speed_factor
		#Update the location of the rect that represents the bullet
		self.rect.x = self.x
			
	def draw_bullet(self):
		"""Draw bullets on the screen"""
		pygame.draw.rect(self.screen, self.color, self.rect)

Topics: Python Attribute Mobile