The examples in this article share the Python aircraft war project for your reference. The specific content is as follows
import gc
import random
import pygame
# Player airplane sprite
import Constants
classHeroPlane(pygame.sprite.Sprite):
def __init__(self, screen):
# Call the parent class initialization method
# pygame.sprite.Sprite.__init__(self)super().__init__()
# window
self.screen = screen
# A picture of a player airplane
self.image = pygame.image.load('./feiji/feiji.png')
# Aircraft rectangle area object
self.rect = self.image.get_rect()
# Coordinates of the upper left corner
self.rect.topleft =[512/2-116/2,600]
# Airplane speed
self.speed =15
# A sprite group stores all bullet sprites
self.bullets = pygame.sprite.Group()
# Initial HP 100
self.blood_value =100
# Mark if the player's plane is over
self.is_remove = False
# The index of the exploded picture starts from 0
self.mIndex =0
# List of explosion pictures
self.bomb_mImages =[]for v inrange(1,15):
# Save all pictures in the list, save each picture twice
self.bomb_mImages.append(pygame.image.load('./feiji/image '+str(v)+'.png'))
self.bomb_mImages.append(pygame.image.load('./feiji/image '+str(v)+'.png'))
def kill_blood(self, kill_value=10):"""Decreased blood volume"""
self.blood_value -= kill_value
print('Got hit, there is still blood%s'% self.blood_value)if self.blood_value <=0:
# Avoid negative blood volume
self.blood_value =0
# Blood volume<=0 set is_remove is True
self.is_remove = True
def key_control(self):"""Press buttons to monitor and operate the aircraft up, down, left, and right, and fire bullets"""
# Listen to keyboard events
key_pressed = pygame.key.get_pressed() #Note that this method can detect the keyboard that has been pressed and not released
if key_pressed[pygame.K_w] or key_pressed[pygame.K_UP]:
# If the top value is less than 0, it will reach the top and don’t move anymore.
if self.rect.top 3:
self.rect.top -= self.speed
if key_pressed[pygame.K_s] or key_pressed[pygame.K_DOWN]:if self.rect.bottom <=768:
self.rect.bottom += self.speed
if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:if self.rect.left 0:
self.rect.left -= self.speed
if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:if self.rect.right <520:
self.rect.right += self.speed
if key_pressed[pygame.K_SPACE]:
# print("space")
# Create 3 bullets
bullet1 =Bullet(self.screen, self.rect.left, self.rect.top,1)
bullet2 =Bullet(self.screen, self.rect.left, self.rect.top,2)
bullet3 =Bullet(self.screen, self.rect.left, self.rect.top,3)
# Add to sprite group
self.bullets.add(bullet1, bullet2, bullet3)
def bomb(self):print('Player airplane exploding')"""Show explosion picture"""
self.screen.blit(self.bomb_mImages[self.mIndex], self.rect)
self.mIndex +=1print('mIndex', self.mIndex)if self.mIndex =len(self.bomb_mImages):
# Play to the end and the explosion ends and returns to True
return True
def update(self):if self.is_remove:print('Player plane hangs up')
# If the player hangs up
if self.bomb():
# End of explosion
print('End of explosion')
self.rect.topleft =[-200,-200]
# Start countdown
pygame.time.set_timer(Constants.game_over_id,1000)
# Point the player plane to None to stop the update
manager.hero = None
else:
self.key_control()
self.display()
def display(self):
# if self.blood_value <=0:
# # If the HP is less than 0, move out of the window
# self.rect.topleft =[-200,-200]
# Display the plane on the window 116*100
self.screen.blit(self.image, self.rect)
# Update the bullet position in the wizard group
self.bullets.update()
# Show all bullets in the sprite group to the window
self.bullets.draw(self.screen)classBullet(pygame.sprite.Sprite):
# path_num indicates which bullet is in the shot
def __init__(self, screen, planex, planey, path_num):
# Call the parent class initialization method
# pygame.sprite.Sprite.__init__(self)super().__init__()
# window
self.screen = screen
# A bullet picture
self.image = pygame.image.load('./feiji/bullet_12.png')
# Bullet rectangle area object
self.rect = self.image.get_rect()
# Coordinates of the upper left corner of the bullet
self.rect.topleft =[planex +48, planey -20]
# Bullet speed
self.speed =15
# path_num indicates which bullet is in the shot
self.path_num = path_num
def update(self):"""Modify bullet coordinates"""
self.rect.top -= self.speed
if self.rect.bottom <0:
# The bullet has been moved out of the top of the screen and now delete the bullet from the wizard group
self.kill()if self.path_num ==1:
pass
elif self.path_num ==2:
# If it is equal to 2, it is the shot on the left
self.rect.left -=10
elif self.path_num ==3:
# If it is equal to 3, it is the shot on the right
self.rect.right +=10
# Enemy Genie
classEnemyPlane(pygame.sprite.Sprite):
# Create class attributes to store all bullets of all aircraft
all_bullets = pygame.sprite.Group()
def __init__(self, screen):
# Call the parent class initialization method
# pygame.sprite.Sprite.__init__(self)super().__init__()
# window
self.screen = screen
# A picture of a player airplane
self.image = pygame.image.load('./feiji/img-plane_5.png')
# Aircraft rectangle area object
self.rect = self.image.get_rect()
# The x coordinate of the upper left corner is random
self.rect.topleft =[random.randint(0,412),0]
# Airplane speed
self.speed =3
# A sprite group stores all bullet sprites
self.bullets = pygame.sprite.Group()
# The left and right direction of the bandit is by default right at the beginning
self.direction ='right'
# Bullet's Elf Group
self.bullets = pygame.sprite.Group()
# Mark whether the enemy aircraft is hit or not to delete
self.is_remove = False
# The index of the exploded picture starts from 0
self.mIndex =0
# List of explosion pictures
self.bomb_mImages =[]for v inrange(1,14):
# Save all pictures in the list, save each picture twice
self.bomb_mImages.append(pygame.image.load('./feiji/image '+str(v)+'.png'))
self.bomb_mImages.append(pygame.image.load('./feiji/image '+str(v)+'.png'))
# Record the explosion location
self.x =0
self.y =0
def auto_move(self):"""Automatic movement"""
# Move Downward
self.rect.bottom += self.speed
# Delete it if the plane moves down out of the boundary
if self.rect.top Manager.height:
self.kill()
# Move left and right in different directions
if self.direction =='right':
self.rect.right +=6
elif self.direction =='left':
self.rect.right -=6
# Change the direction of movement beyond the left and right boundaries
if self.rect.right = Manager.width:
self.direction ='left'if self.rect.left <=0:
self.direction ='right'
def auto_fire(self):
# Use a random number
num = random.randint(1,40)
# Judge if it is equal to 1, fire a bullet, which reduces the probability
if num ==5:
# Generate bandit bullets
bullet =EnemyBullet(self.screen, self.rect.left, self.rect.top)
# Add to sprite group
self.bullets.add(bullet)
# Add the bullet to the all of the class_Used for collision detection in bullets
EnemyPlane.all_bullets.add(bullet)
def bomb(self):"""Show explosion picture"""if self.mIndex =len(self.bomb_mImages):
# Play to the end and the explosion ends and returns to True
return True
self.screen.blit(self.bomb_mImages[self.mIndex],(self.x, self.y))
self.mIndex +=1
def update(self):if self.is_remove:if self.rect.left !=-200:
# Record the location of the explosion
self.x = self.rect.left
self.y = self.rect.top
# If it has been hit, remove the aircraft from the window to prevent collision detection
self.rect.left =-200
self.rect.top =-200
# Show explosion effect
if self.bomb() and not self.bullets:
# If the explosion ends, delete yourself from the wizard group
self.kill()else:
# mobile
self.auto_move()
# Fire
self.auto_fire()
# display
self.display()
self.bullet_show()
def display(self):
# Display the plane on the window 116*100
self.screen.blit(self.image, self.rect)
def bullet_show(self):if self.bullets:
# Bandit bullet update
self.bullets.update()
# Enemy aircraft bullet display
self.bullets.draw(self.screen)classEnemyBullet(pygame.sprite.Sprite):
# path_num indicates which bullet is in the shot
def __init__(self, screen, x, y):
# Call the parent class initialization method
# pygame.sprite.Sprite.__init__(self)super().__init__()
# window
self.screen = screen
# A bullet picture
self.image = pygame.image.load('./feiji/bullet_6.png')
# Bullet rectangle area object
self.rect = self.image.get_rect()
# Coordinates of the upper left corner of the bullet
self.rect.topleft =[x +40, y +60]
# Bullet speed
self.speed =10
def update(self):"""Modify bullet coordinates"""
self.rect.bottom += self.speed
# If the bullet moves down and out of the boundary delete it
if self.rect.top Manager.height:
self.kill()
# Game music
classGameSound(object):
def __init__(self):
pygame.mixer.init() #Music module initialization
pygame.mixer.music.load("./feiji/Jamesketed.mp3")
pygame.mixer.music.set_volume(0.5) #Half the sound
self.__bomb = pygame.mixer.Sound("./feiji/bomb.wav")
def playBackgroundMusic(self):
# Start playing background music-1 means always repeat
pygame.mixer.music.play(-1)
def playBombSound(self):
pygame.mixer.Sound.play(self.__bomb) #Explosion music
classGameBackground(object):
# Initialize the map
def __init__(self, screen):
self.mImage1 = pygame.image.load("./feiji/img_bg_level_4.jpg")
self.mImage2 = pygame.image.load("./feiji/img_bg_level_4.jpg")
# window
self.screen = screen
# Auxiliary mobile map
self.y1 =0
self.y2 =-Manager.height # -768
def update(self):
self.move()
self.draw()
# Move the map
def move(self):
self.y1 +=2
self.y2 +=2if self.y1 = Manager.height:
self.y1 =0if self.y2 =0:
self.y2 =-Manager.height
# Draw a map
def draw(self):
self.screen.blit(self.mImage1,(0, self.y1))
self.screen.blit(self.mImage2,(0, self.y2))classManager:
hero: HeroPlane
# Create width and height
width =512
height =768
def __init__(self):
# pygame is initialized otherwise the font file cannot be found
pygame.init()
# 1 Create a window parameter 1 is width and height, parameter 2 additional parameter parameter 3 is color depth
self.screen = pygame.display.set_mode((self.width, self.height),0,32)
# 2 Create background image objects
# self.background = pygame.image.load('./feiji/img_bg_level_5.jpg')
self.background =GameBackground(self.screen)
# Create an airplane object
self.hero =HeroPlane(self.screen)
# Create a clock object
self.clock = pygame.time.Clock()
# Bandit elves
self.enemys = pygame.sprite.Group()
# Initialize the sound effect object
self.sound =GameSound()
# Define score attributes
self.score =0
# Countdown time
self.over_time =3
def exit(self):
# Execute exit code
pygame.quit()
# Exit of the program
exit()
def new_enemy(self):
# Create a bandit object
enemy =EnemyPlane(self.screen)
# Add to sprite group
self.enemys.add(enemy)
def drawText(self, text, x, y, textHeight=30, fontColor=(255,255,255), backgroudColor=None):
# Obtain font object parameters through font files 1 font file parameters 2 font size
font_obj = pygame.font.Font('./feiji/baddf.ttf', textHeight)
# 1 Whether text 2 is anti-aliased 3 text color 4 background color
text_obj = font_obj.render(text, True, fontColor, backgroudColor) #Configure the text to be displayed
# Get the rect of the object to be displayed
text_rect = text_obj.get_rect()
# Set the coordinates of the display object
text_rect.topleft =(x, y)
# Draw a word to the specified area. Parameter 1 is a text object parameter 2 Rectangle object
self.screen.blit(text_obj, text_rect)
def game_over_timer(self):"""Execute countdown"""
self.over_time -=1if self.over_time ==0:
# Stop countdown
pygame.time.set_timer(Constants.game_over_id,0)
# Restart the game
self.start_game()
def show_over_text(self):print('self.over_time', self.over_time)
# Countdown time displayed at the end of the game
self.drawText('gameover %d'% self.over_time,0, Manager.height /2, textHeight=50,
fontColor=[0,0,0])
def start_game(self):
global manager
# Situation Bandit Bullet Elf Group
EnemyPlane.all_bullets.empty()
manager =Manager()
# Garbage collection prompts the python interpreter to recycle
gc.collect()
manager.main()
def main(self):
# Play background music
self.sound.playBackgroundMusic()
# Ref. 1 eventid is the event id, defined by yourself (0-32) Do not conflict with other event ids of pygame that have been used,
# Parameter 2 is the interval time of timing events, in milliseconds
pygame.time.set_timer(Constants.new_enemy,500)while True:
# Control the number of executions per s
self.clock.tick(60)
# Get the event and handle it
for event in pygame.event.get():
# Determine whether the type of event is exit
if event.type == pygame.QUIT:
# drop out
self.exit()
elif event.type == Constants.new_enemy:
# Equal to 20 means the timer takes effect to add an enemy aircraft
# print('Add an enemy plane')
self.new_enemy()
elif event.type == Constants.game_over_id:print('Countdown 33333')
# Show countdown time
self.game_over_timer()
# 3 Display the background image on the window
# self.screen.blit(self.background,(0,0))
self.background.update()
self.drawText('fraction:%s'% self.score,0,0)if self.hero:
self.drawText('HP:%s'% self.hero.blood_value,0,30)
# Update aircraft
self.hero.update()
# if self.hero.blood_value <=0 and not self.hero.bullets.sprites():
# # Point the player aircraft reference to None and release as soon as possible
# self.hero = None
else:
self.drawText('HP: 0',0,30)
# Update bandit
self.enemys.update()
# If the plane has hung up, the countdown will always be displayed
if not self.hero:
# Show countdown
self.show_over_text()
# Determine whether the player’s aircraft and enemy aircraft are both self.enemys.sprites()Returns the list of sprites corresponding to the sprite group
if self.hero and self.enemys.sprites():
# The list of enemy aircraft that collided returned by the collision detection
collide_enemys = pygame.sprite.spritecollide(self.hero, self.enemys, False, pygame.sprite.collide_mask)if collide_enemys:
# If the list is not empty, it means you have encountered an enemy aircraft
print('Encountered an enemy plane')
# Explosion sound
self.sound.playBombSound()
self.hero.kill_blood(100)for enemy_item in collide_enemys:
# Mark the enemy plane has been hit
enemy_item.is_remove = True
# Determine whether the bullets and enemy aircraft of the player's aircraft and the player's aircraft exist
if self.hero and self.hero.bullets and self.enemys:
# Detect collisions between the player’s aircraft and enemy aircraft
# The return is a dictionary format{<Bullet sprite(in0 groups):[<EnemyPlane sprite(in0 groups)]}
# { Colliding bullet 1:[Enemy plane hit 1 and enemy plane hit 2], The colliding bullet 2:[The enemy plane hit 1, the enemy plane hit 5]}
collode_dict = pygame.sprite.groupcollide(self.hero.bullets, self.enemys, True, False,
pygame.sprite.collide_mask)
# 1 Multiple bullets hit the same plane#2 Different bullets hit different planes#Remove duplicate enemy aircraft for all bonus points
# print(collode_dict)if collode_dict:
# Explosion sound
self.sound.playBombSound()print(self.score)
# Use a set to add enemy aircraft to remove duplicates
enemyset =set()
# Get a list of all enemy planes hit, and then traverse
for v_enemys in collode_dict.values():
# Traverse the list of enemy aircraft
for enemy_item in v_enemys:
# print(id(enemy_item))
enemyset.add(enemy_item)
# Mark the enemy plane has been hit
enemy_item.is_remove = True
# After collision+10 points*Number of enemy aircraft in the set
self.score +=10*len(enemyset)
# Determine the player’s aircraft and enemy aircraft bullets
if self.hero and EnemyPlane.all_bullets:
# Detect the collision between the player and the enemy aircraft
collide_bullets = pygame.sprite.spritecollide(self.hero, EnemyPlane.all_bullets, True,
pygame.sprite.collide_mask)if collide_bullets:
# Decrease 10 if it hits*The number of bullets
self.hero.kill_blood(10*len(collide_bullets))
# 2 Display window
pygame.display.update()if __name__ =='__main__':
manager =Manager()
manager.main()
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts