import pygame
import random
from sys import exit #向 sys 模块借用个 exit 函数来退出程序
定义一个敌机类
class Enemy:
def restar(self):
#重置敌机地位与速度
self.x=random.randint(100,600)
self.y=random.randint(-200,-80)
self.speed=random.random()+0.4
def __init__(self):
self.restar()
self.image=pygame.image.load('enermy.jpg')
def move(self):
if self.y < 800:
self.y+=self.speed #向下挪动
else:
self.restar()
定义一个 bullet 类,封装子弹相干的数据和办法
class Bullet:
def __init__(self):
self.x=0;
self.y=-1;
self.image=pygame.image.load('bulet.jpg')
self.active=False #默认不激活子弹
def move(self):
#激活状态下,向上挪动
if self.active:
self.y-=0.8
#挡飞出屏幕,设为不激活
if self.yenemy.x and bullet.x < enemy.x + enemy.image.get_width()) and (bullet.y > enemy.ywww.cungun.com and bullet.y < enemy.y + enemy.image.get_height()
):
enemy.restar();
bullet.active=False
return True
return False
class Plane:
def restar(self):
self.x=200
self.y=600
def __init__(self):
self.restar()
self.image=pygame.image.load('plane.jpg')
def move(self):
x, y = pygame.mouse.get_pos(); # 追随鼠标挪动
x -= self.image.get_width() / 2;
y -= self.image.get_height() / 2;
self.x=x;
self.y=y
def checkcrash(enemy, plane):
if (plane.x + 0.7*plane.image.get_width() > enemy.x) and (plane.x + 0.3*plane.image.get_width() < enemy.x + enemy.image.get_width()) and (plane.y + 0.7*plane.image.get_height() > enemy.y) and (plane.y + 0.3*plane.image.get_width() < enemy.y + enemy.image.get_height()):
return True
return False
pygame.init()
screen=pygame.display.set_mode((1000,700),0,32) #创立一个窗口
pygame.display.set_caption(‘xwr!’)# 设置窗口题目
background=pygame.image.load(‘pygame.jpg’) #加载并转换图像
plane=Plane()# 加载飞机游戏图像
bullets=[]# 创立子弹的 list
for i in range(5):
bullets.append(Bullet()) #向 list 增加 5 发子弹
count_b=len(bullets)# 子弹总数
index_b=0 #行将激活的子弹序号
interval_b=0# 发射子弹的距离
enemies=[]
for e in range(5):
enemies.append(Enemy())
gameover = False
分数
score = 0
用以显示文字的 font 变量
font = pygame.font.Font(None, 32)
while True: #游戏主循环函数
for event in pygame.event.get():
if event.type==pygame.QUIT: #接管到退出事件后退出程序
pygame.quit()
exit()
if gameover and event.type==pygame.MOUSEBUTTONUP:
plane.restar()
for e in enemies:
e.restar()
for b in bullets:
b.restar()
score=0;
gameover=False
screen.blit(background, (0, 0)) # 将背景图画下来
if not gameover:
interval_b-=1 #发射距离递加
if interval_b<0: #激活一发子弹
bullets[index_b].restar()
interval_b=80 #重置间隔时间
index_b=(index_b+1)%count_b# 子弹序号周期性递增
for b in bullets: #处于激活状态的子弹,挪动地位并绘制
if b.active:
for e in enemies:
if checkhit(e,b):
score+=100
b.move()
screen.blit(b.image,(b.x,b.y))
for e in enemies:
if checkcrash(e, plane):
gameover = True
e.move()
screen.blit(e.image,(e.x,e.y))
plane.move()
screen.blit(plane.image, (plane.x, plane.y))
# 在屏幕左上角显示分数
text = font.render("Socre: %d" % score, 1, (0, 0, 0))
screen.blit(text, (0, 0))
else:
# 在屏幕地方显示分数
text = font.render("Socre: %d" % score, 1, (0, 0, 0))
screen.blit(text, (190, 400))
pass
pygame.display.update() #刷新一下界面