程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python games - aircraft war games (with source code)

編輯:Python

Some written in front P word :

We used python Wrote part of the code of aircraft war ,
Can only show the hero plane , background , Bullets and enemy planes ,
Today, let's put the background music , Destroy the enemy plane , Explosive effects , Score and other related functions are added together ,
The code is a little long , More than 300 lines , Here comes the code you want ?

Programming ideas

The main use of pygame library , Class creation , Function call and so on , Don't talk much , Go to the program .

Programming to realize

python Answering question consulting Learning exchange group 2:660193417###
import pygame # Import dynamic module (.dll .pyd .so) There is no need to follow the package name with the module name
from pygame.locals import *
import time
import random
import sys
# Define constants ( After the definition , No longer change the value )
WINDOW_HEIGHT = 768
WINDOW_WIDTH = 512
enemy_list = []
score = 0
is_restart = False
class Map:
def __init__(self, img_path, window):
self.x = 0
self.bg_img1 = pygame.image.load(img_path)
self.bg_img2 = pygame.image.load(img_path)
self.bg1_y = - WINDOW_HEIGHT
self.bg2_y = 0
self.window = window
def move(self):
# When the map 1 Of y Move axis to 0, Reset
if self.bg1_y >= 0:
self.bg1_y = - WINDOW_HEIGHT
# When the map 2 Of y Move axis to Bottom of window , Reset
if self.bg2_y >= WINDOW_HEIGHT:
self.bg2_y = 0
# Each cycle moves 1 Pixel
self.bg1_y += 3
self.bg2_y += 3
def display(self):
""" Mapping """
self.window.blit(self.bg_img1, (self.x, self.bg1_y))
self.window.blit(self.bg_img2, (self.x, self.bg2_y))
class HeroBullet:
""" Hero bullets """
def __init__(self, img_path, x, y, window):
self.img = pygame.image.load(img_path)
self.x = x
self.y = y
self.window = window
def display(self):
self.window.blit(self.img, (self.x, self.y))
def move(self):
""" The upward flight distance of the bullet """
self.y -= 6
python Answering question consulting Learning exchange group 2:660193417###
def is_hit_enemy(self, enemy):
if pygame.Rect.colliderect(
pygame.Rect(self.x, self.y, 20, 31),
pygame.Rect(enemy.x, enemy.y, 100, 68)
): # Determine whether to cross
return True
else:
return False
class EnemyPlane:
""" Enemy aircraft """
def __init__(self, img_path, x, y, window):
self.img = pygame.image.load(img_path) # Image objects
self.x = x # Aircraft coordinates
self.y = y
self.window = window # The window where the plane is located
self.is_hited = False
self.anim_index = 0
self.hit_sound = pygame.mixer.Sound("E:/ Aircraft battle /baozha.ogg")
def move(self):
self.y += 10
# Reach the lower boundary of the window , Back to the top
if self.y >= WINDOW_HEIGHT:
self.x = random.randint(0, random.randint(0, WINDOW_WIDTH - 100))
self.y = 0
python Answering question consulting Learning exchange group 2:660193417###
def plane_down_anim(self):
""" The enemy plane was hit """
if self.anim_index >= 21: # The animation is finished
self.anim_index = 0
self.img = pygame.image.load(
"E:/ Aircraft battle /img-plane_%d.png" % random.randint(1, 7))
self.x = random.randint(0, WINDOW_WIDTH - 100)
self.y = 0
self.is_hited = False
return
elif self.anim_index == 0:
self.hit_sound.play()
self.img = pygame.image.load(
"E:/ Aircraft battle /bomb-%d.png" % (self.anim_index // 3 + 1))
self.anim_index += 1
def display(self):
""" Mapping """
if self.is_hited:
self.plane_down_anim()
self.window.blit(self.img, (self.x, self.y))
class HeroPlane:
def __init__(self, img_path, x, y, window):
self.img = pygame.image.load(img_path) # Image objects
self.x = x # Aircraft coordinates
self.y = y
self.window = window # The window where the plane is located
self.bullets = [] # Record all bullets fired by the aircraft
self.is_hited = False
self.is_anim_down = False
self.anim_index = 0
def is_hit_enemy(self, enemy):
if pygame.Rect.colliderect(
pygame.Rect(self.x, self.y, 120, 78),
pygame.Rect(enemy.x, enemy.y, 100, 68)
): # Determine whether to cross
return True
else:
return False
def plane_down_anim(self):
""" The enemy plane was hit """
if self.anim_index >= 21: # The animation is finished
self.is_hited = False
self.is_anim_down = True
return
self.img = pygame.image.load(
"E:/ Aircraft battle /bomb-%d.png" % (self.anim_index // 3 + 1))
self.anim_index += 1
def display(self):
""" Mapping """
for enemy in enemy_list:
if self.is_hit_enemy(enemy):
enemy.is_hited = True
self.is_hited = True
self.plane_down_anim()
break
self.window.blit(self.img, (self.x, self.y))
def display_bullets(self):
# Stick a bullet picture
deleted_bullets = []
for bullet in self.bullets:
# Judge Whether the bullet exceeds Upper boundary
if bullet.y >= -31: # There is no boundary
bullet.display()
bullet.move()
else: # Fly out of the boundary
deleted_bullets.append(bullet)
for enemy in enemy_list:
if bullet.is_hit_enemy(enemy): # Determine whether to hit the enemy plane
enemy.is_hited = True
deleted_bullets.append(bullet)
global score
score += 10
break
for out_window_bullet in deleted_bullets:
self.bullets.remove(out_window_bullet)
def move_left(self):
""" Fly left """
if self.x >= 0 and not self.is_hited:
self.x -= 10
def move_right(self):
""" Fly to the right """
if self.x <= WINDOW_WIDTH - 120 and not self.is_hited:
self.x += 10
def move_up(self):
""" Fly up """
if self.y >= 0 and not self.is_hited:
self.y -= 5
def move_down(self):
""" Fly down """
if self.y <= WINDOW_HEIGHT - 78 and not self.is_hited:
self.y += 5
def fire(self):
""" bullets """
# Create bullet objects The bullet x = The plane x + Half the width of the plane - Half the width of the bullet
bullet = HeroBullet("E:/ Aircraft battle /bullet_17.png", self.x +
60 - 10, self.y - 31, self.window)
# Show bullets ( Stick a bullet picture )
bullet.display()
self.bullets.append(bullet) # To prevent the bullet object from being released ( Only local variables refer to objects , As soon as the method is executed, it will release )
class Game:
def __init__(self):
pygame.init()
# Set title
pygame.display.set_caption(" Aircraft battle v1.0")
# Set icon
game_ico = pygame.image.load("E:/ Aircraft battle /app.ico")
pygame.display.set_icon(game_ico)
pygame.mixer.music.load("E:/ Aircraft battle /bg2.ogg")
# The sound effect of the end of the game ( Super Marie )
self.gameover_sound = pygame.mixer.Sound("E:/ Aircraft battle /gameover.wav")
# Loop back the background music
pygame.mixer.music.play(-1)
# create a window set_mode(( Window size ))
self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Create map objects
self.game_map = Map("E:/ Aircraft battle /img_bg_level_%d.jpg" %
random.randint(1, 5), self.window)
# Create objects
self.hero_plane = HeroPlane("E:/ Aircraft battle /hero2.png", 240, 500, self.window)
enemy_plane1 = EnemyPlane("E:/ Aircraft battle /img-plane_%d.png" % random.randint(
1, 7), random.randint(0, WINDOW_WIDTH - 100), 0, self.window)
enemy_plane2 = EnemyPlane("E:/ Aircraft battle /img-plane_%d.png" % random.randint(1, 7), random.randint(0, WINDOW_WIDTH - 100), random.randint(-150, -68),
self.window)
enemy_plane3 = EnemyPlane("E:/ Aircraft battle /img-plane_%d.png" % random.randint(1, 7), random.randint(0, WINDOW_WIDTH - 100), random.randint(-300, -140),
self.window)
enemy_list.append(enemy_plane1)
enemy_list.append(enemy_plane2)
enemy_list.append(enemy_plane3)
self.enemy_list = enemy_list
# Create text object
# self.score_font = pygame.font.SysFont("simhei", 40)
self.score_font = pygame.font.Font("E:/ Aircraft battle /SIMHEI.TTF", 40)
def draw_text(self, content, size, x, y):
# font_obj = pygame.font.SysFont("simhei", size)
font_obj = pygame.font.Font("E:/ Aircraft battle /SIMHEI.TTF", size)
text = font_obj.render(content, 1, (255, 255, 255))
self.window.blit(text, (x, y))
def wait_game_input(self):
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit()
pygame.quit()
elif event.key == K_RETURN:
global is_restart, score
is_restart = True
score = 0
return
def game_start(self):
# Post background picture
self.game_map.display()
self.draw_text(" Aircraft battle ", 40, WINDOW_WIDTH / 2 - 100, WINDOW_HEIGHT / 3)
self.draw_text(" Press Enter Start the game , Esc Quit the game .", 28, WINDOW_WIDTH /3 - 140, WINDOW_HEIGHT /2)
pygame.display.update()
self.wait_game_input()
def game_over(self):
# Stop the background music first
pygame.mixer.music.stop()
# Then play the sound effect
self.gameover_sound.play()
# Post background picture
self.game_map.display()
self.draw_text(" The plane was shot down , The score is %d" % score, 28, WINDOW_WIDTH / 3 - 100, WINDOW_HEIGHT / 3)
self.draw_text(" Press Enter restart , Esc Quit the game .", 28, WINDOW_WIDTH / 3 - 140, WINDOW_HEIGHT / 2)
pygame.display.update()
self.wait_game_input()
self.gameover_sound.stop()
def key_control(self):
# Get events , For example, keys, etc Display interface first , Then according to the obtained Events , Modify the interface effect
for event in pygame.event.get():
# Determine whether the exit button is clicked
if event.type == QUIT:
sys.exit() # Let the program terminate
pygame.quit()
# Determine if the key is pressed
elif event.type == KEYDOWN:
# Check whether the key is a space bar
if event.key == K_SPACE:
self.hero_plane.fire()
# Get the condition of continuous pressing
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_LEFT]:
self.hero_plane.move_left()
if pressed_keys[pygame.K_RIGHT]:
self.hero_plane.move_right()
if pressed_keys[pygame.K_UP]:
self.hero_plane.move_up()
if pressed_keys[pygame.K_DOWN]:
self.hero_plane.move_down()
def display(self):
# Paste the background picture
self.game_map.display()
self.game_map.move()
# Paste the plane map
self.hero_plane.display()
self.hero_plane.display_bullets()
# Post enemy aircraft map
for enemy in enemy_list:
enemy.display()
# Let the enemy plane move
if not enemy.is_hited:
enemy.move()
# Post score text
score_text = self.score_font.render(" score :%d" % score, 1, (255, 255, 255))
self.window.blit(score_text, (10, 10))
# Refresh the interface Without refreshing, the displayed content will not be updated
pygame.display.update()
def run(self):
if is_restart == False:
self.game_start()
while True:
# display
self.display()
if self.hero_plane.is_anim_down:
self.hero_plane.is_anim_down = False
global enemy_list
enemy_list = []
break
# Keyboard control
self.key_control()
# Each cycle , Let the program sleep for a while
time.sleep(0.01)
self.game_over()
def main():
""" The main function Generally, the entry of the program """
# Run the game
while True:
# Create game objects
game = Game()
game.run()
if __name__ == '__main__': # Determine whether to actively execute the file
main()
import pygame # Import dynamic module (.dll .pyd .so) There is no need to follow the package name with the module name
from pygame.locals import *
import time
import random
import sys
# Define constants ( After the definition , No longer change the value )
WINDOW_HEIGHT = 768
WINDOW_WIDTH = 512
enemy_list = []
score = 0
is_restart = False
class Map:
def __init__(self, img_path, window):
self.x = 0
self.bg_img1 = pygame.image.load(img_path)
self.bg_img2 = pygame.image.load(img_path)
self.bg1_y = - WINDOW_HEIGHT
self.bg2_y = 0
self.window = window
def move(self):
# When the map 1 Of y Move axis to 0, Reset
if self.bg1_y >= 0:
self.bg1_y = - WINDOW_HEIGHT
# When the map 2 Of y Move axis to Bottom of window , Reset
if self.bg2_y >= WINDOW_HEIGHT:
self.bg2_y = 0
# Each cycle moves 1 Pixel
self.bg1_y += 3
self.bg2_y += 3
def display(self):
""" Mapping """
self.window.blit(self.bg_img1, (self.x, self.bg1_y))
self.window.blit(self.bg_img2, (self.x, self.bg2_y))
class HeroBullet:
""" Hero bullets """
def __init__(self, img_path, x, y, window):
self.img = pygame.image.load(img_path)
self.x = x
self.y = y
self.window = window
def display(self):
self.window.blit(self.img, (self.x, self.y))
def move(self):
""" The upward flight distance of the bullet """
self.y -= 6
def is_hit_enemy(self, enemy):
if pygame.Rect.colliderect(
pygame.Rect(self.x, self.y, 20, 31),
pygame.Rect(enemy.x, enemy.y, 100, 68)
): # Determine whether to cross
return True
else:
return False
class EnemyPlane:
""" Enemy aircraft """
def __init__(self, img_path, x, y, window):
self.img = pygame.image.load(img_path) # Image objects
self.x = x # Aircraft coordinates
self.y = y
self.window = window # The window where the plane is located
self.is_hited = False
self.anim_index = 0
self.hit_sound = pygame.mixer.Sound("E:/ Aircraft battle /baozha.ogg")
def move(self):
self.y += 10
# Reach the lower boundary of the window , Back to the top
if self.y >= WINDOW_HEIGHT:
self.x = random.randint(0, random.randint(0, WINDOW_WIDTH - 100))
self.y = 0
def plane_down_anim(self):
""" The enemy plane was hit """
if self.anim_index >= 21: # The animation is finished
self.anim_index = 0
self.img = pygame.image.load(
"E:/ Aircraft battle /img-plane_%d.png" % random.randint(1, 7))
self.x = random.randint(0, WINDOW_WIDTH - 100)
self.y = 0
self.is_hited = False
return
elif self.anim_index == 0:
self.hit_sound.play()
self.img = pygame.image.load(
"E:/ Aircraft battle /bomb-%d.png" % (self.anim_index // 3 + 1))
self.anim_index += 1
def display(self):
""" Mapping """
if self.is_hited:
self.plane_down_anim()
self.window.blit(self.img, (self.x, self.y))
class HeroPlane:
def __init__(self, img_path, x, y, window):
self.img = pygame.image.load(img_path) # Image objects
self.x = x # Aircraft coordinates
self.y = y
self.window = window # The window where the plane is located
self.bullets = [] # Record all bullets fired by the aircraft
self.is_hited = False
self.is_anim_down = False
self.anim_index = 0
def is_hit_enemy(self, enemy):
if pygame.Rect.colliderect(
pygame.Rect(self.x, self.y, 120, 78),
pygame.Rect(enemy.x, enemy.y, 100, 68)
): # Determine whether to cross
return True
else:
return False
def plane_down_anim(self):
""" The enemy plane was hit """
if self.anim_index >= 21: # The animation is finished
self.is_hited = False
self.is_anim_down = True
return
self.img = pygame.image.load(
"E:/ Aircraft battle /bomb-%d.png" % (self.anim_index // 3 + 1))
self.anim_index += 1
def display(self):
""" Mapping """
for enemy in enemy_list:
if self.is_hit_enemy(enemy):
enemy.is_hited = True
self.is_hited = True
self.plane_down_anim()
break
self.window.blit(self.img, (self.x, self.y))
def display_bullets(self):
# Stick a bullet picture
deleted_bullets = []
for bullet in self.bullets:
# Judge Whether the bullet exceeds Upper boundary
if bullet.y >= -31: # There is no boundary
bullet.display()
bullet.move()
else: # Fly out of the boundary
deleted_bullets.append(bullet)
for enemy in enemy_list:
if bullet.is_hit_enemy(enemy): # Determine whether to hit the enemy plane
enemy.is_hited = True
deleted_bullets.append(bullet)
global score
score += 10
break
for out_window_bullet in deleted_bullets:
self.bullets.remove(out_window_bullet)
def move_left(self):
""" Fly left """
if self.x >= 0 and not self.is_hited:
self.x -= 10
def move_right(self):
""" Fly to the right """
if self.x <= WINDOW_WIDTH - 120 and not self.is_hited:
self.x += 10
def move_up(self):
""" Fly up """
if self.y >= 0 and not self.is_hited:
self.y -= 5
def move_down(self):
""" Fly down """
if self.y <= WINDOW_HEIGHT - 78 and not self.is_hited:
self.y += 5
def fire(self):
""" bullets """
# Create bullet objects The bullet x = The plane x + Half the width of the plane - Half the width of the bullet
bullet = HeroBullet("E:/ Aircraft battle /bullet_17.png", self.x +
60 - 10, self.y - 31, self.window)
# Show bullets ( Stick a bullet picture )
bullet.display()
self.bullets.append(bullet) # To prevent the bullet object from being released ( Only local variables refer to objects , As soon as the method is executed, it will release )
class Game:
def __init__(self):
pygame.init()
# Set title
pygame.display.set_caption(" Aircraft battle v1.0")
# Set icon
game_ico = pygame.image.load("E:/ Aircraft battle /app.ico")
pygame.display.set_icon(game_ico)
pygame.mixer.music.load("E:/ Aircraft battle /bg2.ogg")
# The sound effect of the end of the game ( Super Marie )
self.gameover_sound = pygame.mixer.Sound("E:/ Aircraft battle /gameover.wav")
# Loop back the background music
pygame.mixer.music.play(-1)
# create a window set_mode(( Window size ))
self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Create map objects
self.game_map = Map("E:/ Aircraft battle /img_bg_level_%d.jpg" %
random.randint(1, 5), self.window)
# Create objects
self.hero_plane = HeroPlane("E:/ Aircraft battle /hero2.png", 240, 500, self.window)
enemy_plane1 = EnemyPlane("E:/ Aircraft battle /img-plane_%d.png" % random.randint(
1, 7), random.randint(0, WINDOW_WIDTH - 100), 0, self.window)
enemy_plane2 = EnemyPlane("E:/ Aircraft battle /img-plane_%d.png" % random.randint(1, 7), random.randint(0, WINDOW_WIDTH - 100), random.randint(-150, -68),
self.window)
enemy_plane3 = EnemyPlane("E:/ Aircraft battle /img-plane_%d.png" % random.randint(1, 7), random.randint(0, WINDOW_WIDTH - 100), random.randint(-300, -140),
self.window)
enemy_list.append(enemy_plane1)
enemy_list.append(enemy_plane2)
enemy_list.append(enemy_plane3)
self.enemy_list = enemy_list
# Create text object
# self.score_font = pygame.font.SysFont("simhei", 40)
self.score_font = pygame.font.Font("E:/ Aircraft battle /SIMHEI.TTF", 40)
def draw_text(self, content, size, x, y):
# font_obj = pygame.font.SysFont("simhei", size)
font_obj = pygame.font.Font("E:/ Aircraft battle /SIMHEI.TTF", size)
text = font_obj.render(content, 1, (255, 255, 255))
self.window.blit(text, (x, y))
def wait_game_input(self):
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit()
pygame.quit()
elif event.key == K_RETURN:
global is_restart, score
is_restart = True
score = 0
return
def game_start(self):
# Post background picture
self.game_map.display()
self.draw_text(" Aircraft battle ", 40, WINDOW_WIDTH / 2 - 100, WINDOW_HEIGHT / 3)
self.draw_text(" Press Enter Start the game , Esc Quit the game .", 28, WINDOW_WIDTH /3 - 140, WINDOW_HEIGHT /2)
pygame.display.update()
self.wait_game_input()
def game_over(self):
# Stop the background music first
pygame.mixer.music.stop()
# Then play the sound effect
self.gameover_sound.play()
# Post background picture
self.game_map.display()
self.draw_text(" The plane was shot down , The score is %d" % score, 28, WINDOW_WIDTH / 3 - 100, WINDOW_HEIGHT / 3)
self.draw_text(" Press Enter restart , Esc Quit the game .", 28, WINDOW_WIDTH / 3 - 140, WINDOW_HEIGHT / 2)
pygame.display.update()
self.wait_game_input()
self.gameover_sound.stop()
def key_control(self):
# Get events , For example, keys, etc Display interface first , Then according to the obtained Events , Modify the interface effect
for event in pygame.event.get():
# Determine whether the exit button is clicked
if event.type == QUIT:
sys.exit() # Let the program terminate
pygame.quit()
# Determine if the key is pressed
elif event.type == KEYDOWN:
# Check whether the key is a space bar
if event.key == K_SPACE:
self.hero_plane.fire()
# Get the condition of continuous pressing
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_LEFT]:
self.hero_plane.move_left()
if pressed_keys[pygame.K_RIGHT]:
self.hero_plane.move_right()
if pressed_keys[pygame.K_UP]:
self.hero_plane.move_up()
if pressed_keys[pygame.K_DOWN]:
self.hero_plane.move_down()
def display(self):
# Paste the background picture
self.game_map.display()
self.game_map.move()
# Paste the plane map
self.hero_plane.display()
self.hero_plane.display_bullets()
# Post enemy aircraft map
for enemy in enemy_list:
enemy.display()
# Let the enemy plane move
if not enemy.is_hited:
enemy.move()
# Post score text
score_text = self.score_font.render(" score :%d" % score, 1, (255, 255, 255))
self.window.blit(score_text, (10, 10))
# Refresh the interface Without refreshing, the displayed content will not be updated
pygame.display.update()
def run(self):
if is_restart == False:
self.game_start()
while True:
# display
self.display()
if self.hero_plane.is_anim_down:
self.hero_plane.is_anim_down = False
global enemy_list
enemy_list = []
break
# Keyboard control
self.key_control()
# Each cycle , Let the program sleep for a while
time.sleep(0.01)
self.game_over()
def main():
""" The main function Generally, the entry of the program """
# Run the game
while True:
# Create game objects
game = Game()
game.run()
if __name__ == '__main__': # Determine whether to actively execute the file
main()
# The code is a little long , You have to pull down hard ...

design sketch

Last

This is the end of the little game of aircraft war that I share with you today , Put the code on it , If you like, take it and try it .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved