- 帖子
- 4
- 精华
- 0
- 积分
- 24
- 阅读权限
- 10
- 注册时间
- 2019-1-4
- 最后登录
- 2019-6-8
|
# -*- coding: cp936 -*-
import pygame
import random
from sys import 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()
screen = pygame.display.set_mode((450, 800), 0, 32)
pygame.display.set_caption("hello woeld")
# 加载相关图像
sky = 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(sky,(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()
老师,为什么我run出来的结果还是只有一颗子弹呢,看了好多遍都没找到问题...
|
|