use Python Achieve wechat version of the aircraft war writing | a highlander

source :Python technology 「ID: pythonall」

 use Python Achieve wechat version of the aircraft war

2013 Annual wechat 5.0 Version built in a classic game - Gray and black version of the aircraft war , It's called wechat classic airplane war , In this version, wechat even set welcome as this small game , The user's first landing will directly enter the aircraft war games , Once launched, the game is also very popular , There were also many classic quotations at that time .

We want to achieve the aircraft war this small game , The main need is to use a third-party module pygame, Install and use pip install pygame that will do .

role model

The role of this small game is relatively simple , It mainly includes three parts : The player 、 The enemy and the bullets .

Let's define a bullet class first , Class includes bullet styles 、 Moving speed, etc , The code implementation is as follows :

# Bullets
class Bullet(pygame.sprite.Sprite):
def __init__(self, img, pos):
pygame.sprite.Sprite.__init__(self)
self.image = img
# Set the area of the picture
self.rect = self.image.get_rect()
self.rect.midbottom = pos
self.speed = 10
def move(self):
self.rect.top -= self.speed

Now let's define enemy humans , Class mainly includes enemy aircraft styles 、 Movement speed 、 Location, etc , The code implementation is as follows :

# Enemy human
class Enemy(pygame.sprite.Sprite):
def __init__(self, img, explosion_img, pos):
pygame.sprite.Sprite.__init__(self)
self.image = img
self.rect = self.image.get_rect()
self.rect.topleft = pos
self.explosion_img = explosion_img
self.speed = 2
# Set the kill sequence
self.explosion_index = 0
def move(self):
# The enemy's bullets can only go straight down
self.rect.top += self.speed

Let's go on to define the player class , Class includes the initial position of the aircraft 、 Mobile method 、 Whether it was hit by the enemy plane, etc , The code implementation is as follows :

# Player class
class Player(pygame.sprite.Sprite):
def __init__(self, img, rect, pos):
pygame.sprite.Sprite.__init__(self)
self.image = []
# Separate the parts of the plane picture
for i in range(len(rect)):
self.image.append(img.subsurface(rect[i]).convert_alpha())
# Get the area of the plane
self.rect = rect[0]
self.rect.topleft = pos
self.speed = 8
# Generate sprite group instance
self.bullets = pygame.sprite.Group()
self.img_index = 0
# Judge whether the plane was hit
self.is_hit = False
def shoot(self, img):
bullet = Bullet(img, self.rect.midtop)
# Add bullet instance to player's bullet group
self.bullets.add(bullet)
def moveUp(self):
# When it comes to the top , Set the top to 0
if self.rect.top <= 0:
self.rect.top = 0
else:
self.rect.top -= self.speed
def moveDown(self):
# When it comes to the bottom , Set to constant all the time
if self.rect.top >= SCREEN_HEIGHT - self.rect.height:
self.rect.top = SCREEN_HEIGHT - self.rect.height
else:
self.rect.top += self.speed
def moveLeft(self):
# When it comes to the left , All the way to the left
if self.rect.left <= 0:
self.rect.left = 0
else:
self.rect.left -= self.speed
def moveRight(self):
# When it comes to the right , Stop to the right
if self.rect.left >= SCREEN_WIDTH - self.rect.width:
self.rect.left = SCREEN_WIDTH - self.rect.width
else:
self.rect.left += self.speed

Running logic

Now we've defined the characters of the game model 了 , Next we can start with the characters model、 Image material and some constants for some initialization operations , The code implementation is as follows :

# Set the width of the screen
SCREEN_WIDTH = 450
# Set the height of the screen
SCREEN_HEIGHT = 600
# Initialize window
pygame.init()
# Set the window title
pygame.display.set_caption(" Aircraft battle ")
# Set the screen size
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
# hide cursor
pygame.mouse.set_visible(False)
# Set the background
bg = pygame.image.load("resources/image/bg.png")
# Set the picture of the end of the game
bg_game_over = pygame.image.load("resources/image/bg_game_over.png")
# Loading aircraft resource images
img_plane = pygame.image.load("resources/image/shoot.png")
img_start = pygame.image.load("resources/image/start.png")
img_pause = pygame.image.load("resources/image/pause.png")
img_icon = pygame.image.load("resources/image/plane.png").convert_alpha()
# By the way, set the window
pygame.display.set_icon(img_icon)
# Initialize the aircraft area
player_rect = []
player_rect.append(pygame.Rect(0, 99, 102, 126))
player_rect.append(pygame.Rect(165, 360, 102, 126))
# Player explosion picture
player_rect.append(pygame.Rect(165, 234, 102, 126))
player_rect.append(pygame.Rect(330, 624, 102, 126))
player_rect.append(pygame.Rect(330, 498, 102, 126))
player_rect.append(pygame.Rect(432, 624, 102, 126))
# Initialization position
player_pos = [200, 450]
# Generate player class
player = Player(img_plane, player_rect, player_pos)
# Set the bullet box
bullet_rect = pygame.Rect(1004, 987, 9, 21)
# Loading bullet pictures
bullet_img = img_plane.subsurface(bullet_rect)
# Set the enemy box
enemy_rect = pygame.Rect(534, 612, 57, 43)
# Set up enemy pictures
enemy_img = img_plane.subsurface(enemy_rect)
# Set up a picture of the enemy being hit
enemy_explosion_imgs = []
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(267, 347, 57, 43)))
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(873, 697, 57, 43)))
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(267, 296, 57, 43)))
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(930, 697, 57, 43)))
# Set up the enemy spirit group
enemies = pygame.sprite.Group()
# Set up the enemy's hit spirit group
enemies_explosion = pygame.sprite.Group()
# Set the firing frequency
shoot_frequency = 0
# Set the enemy frequency
enemy_frequency = 0
# Set the order of the player's hit pictures
player_explosion_index = 16
score = 0
running = True
is_pause = False
is_game_over = False
clock = pygame.time.Clock()

Last , Let's take a look at the most important part of the game - The logic of the game , It mainly includes : Generation and operation of enemy aircraft 、 The generation and operation of bullets 、 Generating score 、 How to deal with the game state ( Pause 、 Reset 、 end ) etc. , The specific code implementation is as follows :

# Start the game cycle
while running:
# Set the game frame rate to 60
clock.tick(60)
if not is_pause and not is_game_over:
if not player.is_hit:
# Set up continuous fire , Because every second 60 frame ,15/60=0.25 One shot per second
if shoot_frequency % 15 == 0:
player.shoot(bullet_img)
shoot_frequency += 1
# When the set firing frequency is greater than 15, Zeroing
if shoot_frequency >= 15:
shoot_frequency = 0
# Control the frequency of the generated enemy aircraft
if enemy_frequency % 50 == 0:
# Set the location of the enemy plane
enemy_pos = [random.randint(0, SCREEN_WIDTH - enemy_rect.width), 0]
enemy = Enemy(enemy_img, enemy_explosion_imgs, enemy_pos)
enemies.add(enemy)
enemy_frequency += 1
if enemy_frequency >= 100:
enemy_frequency = 0
# Control the display operation of the bullet
for bullet in player.bullets:
bullet.move()
if bullet.rect.bottom < 0:
player.bullets.remove(bullet)
# Control the operation of enemy aircraft
for enemy in enemies:
enemy.move()
# Judge whether the enemy plane collides with the player's plane
if pygame.sprite.collide_circle(enemy, player):
enemies_explosion.add(enemy)
enemies.remove(enemy)
player.is_hit = True
# Set player's plane destroyed
is_game_over = True
# Judge whether the enemy plane is in the interface
if enemy.rect.top < 0:
enemies.remove(enemy)
# Set up when the enemy plane collides with the player's plane bullet , Return the instance of the attacked enemy plane
enemy_explosion = pygame.sprite.groupcollide(enemies, player.bullets, 1, 1)
for enemy in enemy_explosion:
enemies_explosion.add(enemy)
# Draw screen
screen.fill(0)
# Add a background image
screen.blit(bg, (0, 0))
# Add player plane image to screen
if not player.is_hit:
screen.blit(player.image[int(player.img_index)], player.rect)
player.img_index = shoot_frequency / 8
else:
if player_explosion_index > 47:
is_game_over = True
else:
player.img_index = player_explosion_index / 8
screen.blit(player.image[int(player.img_index)], player.rect)
player_explosion_index += 1
# The effect of the enemy plane being hit by the submunition shows that
for enemy in enemies_explosion:
if enemy.explosion_index == 0:
pass
if enemy.explosion_index > 7:
enemies_explosion.remove(enemy)
score += 100
continue
# Display the picture when the enemy plane is attacked
screen.blit(enemy.explosion_img[int(enemy.explosion_index / 2)], enemy.rect)
enemy.explosion_index += 1
# Show bullets
player.bullets.draw(screen)
# Show enemy aircraft
enemies.draw(screen)
# The display of scores
score_font = pygame.font.Font(None, 36)
score_text = score_font.render(str(score), True, (128, 128, 128))
# Set the text box
text_rect = score_text.get_rect()
# Where to put the text
text_rect.topleft = [20, 10]
# Show the score
screen.blit(score_text, text_rect)
left, middle, right = pygame.mouse.get_pressed()
# Pause the game
if right == True and not is_game_over:
is_pause = True
if left == True:
# Reset game
if is_game_over:
is_game_over = False
player_rect = []
player_rect.append(pygame.Rect(0, 99, 102, 126))
player_rect.append(pygame.Rect(165, 360, 102, 126))
player_rect.append(pygame.Rect(165, 234, 102, 126))
player_rect.append(pygame.Rect(330, 624, 102, 126))
player_rect.append(pygame.Rect(330, 498, 102, 126))
player_rect.append(pygame.Rect(432, 624, 102, 126))
player = Player(img_plane, player_rect, player_pos)
bullet_rect = pygame.Rect(1004, 987, 9, 21)
bullet_img = img_plane.subsurface(bullet_rect)
enemy_rect = pygame.Rect(534, 612, 57, 43)
enemy_img = img_plane.subsurface(enemy_rect)
enemy_explosion_imgs = []
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(267, 347, 57, 43)))
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(873, 697, 57, 43)))
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(267, 296, 57, 43)))
enemy_explosion_imgs.append(img_plane.subsurface(pygame.Rect(930, 697, 57, 43)))
enemies = pygame.sprite.Group()
enemies_explosion = pygame.sprite.Group()
score = 0
shoot_frequency = 0
enemy_frequency = 0
player_explosion_index = 16
# Keep playing
if is_pause:
is_pause = False
# Game over
if is_game_over:
font = pygame.font.SysFont(" Microsoft YaHei ", 48)
text = font.render("Score: " + str(score), True, (255, 0, 0))
text_rect = text.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery + 70
# Show the end of the game
screen.blit(bg_game_over, (0, 0))
# Show scores
screen.blit(text, text_rect)
font = pygame.font.SysFont(" Microsoft YaHei ", 40)
text = font.render("Press Left Mouse to Restart", True, (255, 0, 0))
text_rect = text.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery + 150
screen.blit(text, text_rect)
# The refresh screen
pygame.display.update()
# Deal with game exit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if not is_pause and not is_game_over:
key = pygame.key.get_pressed()
if key[K_w] or key[K_UP]:
player.moveUp()
if key[K_s] or key[K_DOWN]:
player.moveDown()
if key[K_a] or key[K_LEFT]:
player.moveLeft()
if key[K_d] or key[K_RIGHT]:
player.moveRight()

Let's look at the implementation effect :

 use Python Achieve wechat version of the aircraft war

summary

In this article we use Python It realizes the basic functions of wechat aircraft war , We are interested in the source code can be obtained to play their own , If you are not satisfied with where the game is implemented , You can modify it yourself .