用Python语言编写飞机大战,主要编写发射子弹。完成后相关代码如下:
import pygame
from pygame.locals import *
import time
class HeroPlane:
def __init__(self, scree):
self.x = 190
self.y = 576
self.scree = scree
self.image = pygame.image.load("./feiji/hero1.png")
# 表示我机发射出的子弹
self.bullet_list = [] # 存储我机发射出的子弹,用于判断是否击中敌机
# 用于显示飞机
def display(self):
self.scree.blit(self.image, (self.x, self.y)) # 显示我机
# 用于显示子弹
for bullet in self.bullet_list:
bullet.display()
bullet.move()
# 判断子弹是否超过了边界,
if bullet.judge():
self.bullet_list.remove(bullet)
def move_left(self):
self.x -= 5
def move_right(self):
self.x += 5
# 我机发射子弹
def fire(self):
self.bullet_list.append(Bullet(self.scree, self.x, self.y))
创建我机的子弹
class Bullet:
def __init__(self, scree, x, y):
self.x = x + 40
self.y = y - 22
self.scree = scree
self.image = pygame.image.load("./feiji/bullet.png")
# 用于显示子弹
def display(self):
self.scree.blit(self.image, (self.x, self.y)) # 显示我机
# 子弹向上移动
def move(self):
self.y -= 20
# 判断子弹的 y值,是否超越边界
def judge(self):
if self.y < 0:
return True
else:
return False
def key_control(hero):
for event in pygame.event.get():
if event.type == QUIT:
print("exit")
exit()
elif event.type == KEYDOWN:
if event.key == K_a or event.key == K_LEFT:
print('left')
hero.move_left()
elif event.key == K_d or event.key == K_RIGHT:
print('right')
hero.move_right()
# 检测按键是否是空格键
elif event.key == K_SPACE:
print('space')
hero.fire() # 我机开火
def main():
scree = pygame.display.set_mode((480, 700), 0, 32)
background = pygame.image.load("./feiji/background.png")
hero = HeroPlane(scree)
while True:
scree.blit(background, (0, 0))
# 显示我机
hero.display()
key_control(hero)
pygame.display.update()
time.sleep(0.05)
if name == 'main':
main()