Crossin的编程教室
标题:
打飞机怎么运行后没有子弹呢?也没有报错
[打印本页]
作者:
hhjandjd
时间:
2018-2-7 09:53
标题:
打飞机怎么运行后没有子弹呢?也没有报错
#_*_coding:utf-8 _*_
import
pygame
#导入pygame库
from
sys
import
exit
import
random
#向sys模块借一个exit函数用来退出程序
class
Bullet
:
def
__init__
(
self
):
self
.x=
0
self
.y=-
1
self
.image=pygame.image.load(
'bullet.png'
).convert_alpha()
#默认不激活
self
.active=
False
def
move
(
self
):
#激活状态下,向上移动
if
self
.active:
self
.y=-
3
#当飞出屏幕,则设为不激活
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()
pygame.init()
#初始化pygame,为使用硬件做准备
screen=pygame.display.set_mode((
450
,
800
)
,
0
,
32
)
#创建一个窗口,窗口的大小和背景图片大小一样
pygame.display.set_caption(
'Hello,World!'
)
#设置窗口标题
background=pygame.image.load(
'back.jpg'
).convert()
#加载并转换图像
plane=pygame.image.load(
'plane.png'
).convert_alpha()
#加载飞机图像
#创建子弹的list
bullets=[]
#向list中添加5发子弹
for
i
in
range
(
5
):
bullets.append(Bullet())
#子弹的总数
count_b=
len
(bullets)
#即将激活的子弹序号
index_b=
0
#发射子弹的间隔
interval_b=
0
enemy=Enemy()
while
True
:
#游戏主循环
for
event
in
pygame.event.get():
if
event.type==pygame.QUIT:
#接收到退出事件后退出程序
pygame.quit()
exit()
screen.blit(background
,
(
0
,
0
))
#将背景图画上去
#发射间隔递减
interval_b-=
1
#当间隔小于0时,激活一发子弹
if
interval_b<
0
:
bullets[index_b].restart()
#重置间隔时间
interval_b=
100
#子弹序号周期性递增
index_b=(index_b+
1
)%count_b
#判断每个子弹的状态
for
b
in
bullets:
#处于激活状态的子弹,移动位置并绘制
if
b.active:
b.move()
screen.blit(b.image
,
(b.x
,
b.y))
#更新敌机位置
enemy.move()
screen.blit(enemy.image
,
(enemy.x
,
enemy.y))
x
,
y=pygame.mouse.get_pos()
x-=plane.get_width()/
2
y-=plane.get_height()/
2
#计算飞机的左上角位置
screen.blit(plane
,
(x
,
y))
#把飞机画到屏幕上
pygame.display.update()
#刷新一下画面
作者:
crossin先生
时间:
2018-2-8 14:38
增加输出信息,确认是数据问题还是显示问题,逐步定位问题所在
作者:
hhjandjd
时间:
2018-2-9 10:43
好的 我试一试
欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/)
Powered by Discuz! X2.5