- 帖子
- 2
- 精华
- 0
- 积分
- 56
- 阅读权限
- 20
- 注册时间
- 2018-7-9
- 最后登录
- 2018-9-20
|
请问 游戏能正常运行 但是碰撞之后 游戏没有陷入空白 只是飞机不能发子弹了 这是什么问题 代码如下:
import pygame
import random
from sys import exit
#定义一个bullet类,封装子弹相关的数据和方法
class Bullet:
def __init__(self):
self.x = 0
self.y = -1
self.image = pygame.image.load('bullet.png').convert_alpha()
#初始化成员变量,x,y,image
self.active = False
def move(self):
#激活状态下,向上移动
if self.active:
self.y -= 2
#当飞出屏幕,就设为不激活
if self.y < 0:
self.active = False
def restart(self):
#重置子弹位置
mouseX,mouseY = pygame.mouse.get_pos()
self.x = mouseX - self.image.get_width() / 2
self.y = mouseY - self.image.get_height() / 2
#激活子弹
self.active = True
class Enemy:
def restart(self):
#重置敌机位置和速度
self.x = random.randint(50,400)
self.y = random.randint(-200,-50)
self.speed = random.random() + 0.1
def __init__(self):
#初始化
self.restart()
self.image = pygame.image.load('enemy.png').convert_alpha()
def move(self):
if self.y < 800:
#向下移动
self.y += self.speed
else:
self.restart()
class Plane:
def restart(self):
self.x = 200
self.y = 600
def __init__(self):
self.restart()
self.image = pygame.image.load('plane.jpg').convert_alpha()
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 checkHit(enemy, bullet):
if (bullet.x > enemy.x and bullet.x < enemy.x + enemy.image.get_width()) and (
bullet.y > enemy.y and bullet.y < enemy.y + enemy.image.get_height()
):
enemy.restart()
bullet.active = False
#检测敌机与本地是否相撞
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_height() < enemy.y + enemy.image.get_height()
):
return True
return False
pygame.init()
screen = pygame.display.set_mode((450,800),0,32)
#创建了一个窗口
pygame.display.set_caption("hello world!")
#设置窗口标题
background = pygame.image.load('z.jpg').convert()
#创建Plane对象
plane = Plane()
bullets =[]
#向list中添加5发子弹
for i in range(5):
bullets.append(Bullet())
#子弹总数
count_b = len(bullets)
#即将激活子弹序号
index_b = 0
#发射子弹的间隔
interval_b = 0
#创建敌机list
enemies = []
#添加5个敌机
for i in range(5):
enemies.append(Enemy())
#增加记录游戏是否结束变量
gameover = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(background, (0, 0))
#当gameover为False时,游戏逻辑正常运行
if not gameover:
#发射间隔递减
interval_b -= 1
#当间隔小于0时,激活已发子弹
if interval_b < 0:
bullets[index_b].restart()
#重置间隔时间
interval_b = 200
#子弹序号周期性递减
index_b = (index_b + 1) % count_b
#判断每个子弹的状态
for b in bullets:
#处于激活状态的子弹,移动位置并绘制
if b.active:
#检查每一刻active的子弹是否与敌机碰撞
for e in enemies:
checkHit(e,b)
b.move()
screen.blit(b.image,(b.x,b.y))
for e in enemies:
#如果撞上敌机,设gameover为True
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))
else:
#待处理
pass
pygame.display.update() |
|