- 帖子
- 6
- 精华
- 0
- 积分
- 28
- 阅读权限
- 10
- 注册时间
- 2018-1-12
- 最后登录
- 2018-2-3
|
- # -*- coding:utf-8 -*-
- import random
- from sys import exit
- import pygame
- # 子弹类
- class Bullet:
- def __init__(self):
- self.x1 = 0
- self.y1 = -1
- self.x2 = -1
- self.y2 = -1
- self.x3 = 1
- self.y3 = -1
- self.image = pygame.image.load('bullet.png').convert_alpha()
- # 默认不激活
- self.active = False
- def move(self):
- # 激活状态下,向上移动
- if self.active:
- self.y1 -= 3
- self.y2 -= 3
- self.y3 -= 3
- # 当飞出屏幕,就设为不激活
- if self.y1 < 0:
- self.active = False
- def restart(self):
- # 重置子弹位置
- mouseX, mouseY = pygame.mouse.get_pos()
- pygame.mouse.set_visible(False)
- self.x1 = mouseX - self.image.get_width() / 2 - 10
- self.y1 = mouseY - self.image.get_height() / 2
- self.x2 = mouseX - self.image.get_width() / 2
- self.y2 = mouseY - self.image.get_height() / 2
- self.x3 = mouseX - self.image.get_width() / 2 + 10
- self.y3 = mouseY - self.image.get_height() / 2
- # 激活子弹
- self.active = True
- # 敌机类
- class Enemy:
- 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()
- def restart(self):
- self.x = random.randint(50, 400)
- self.y = random.randint(-200, -50)
- self.speed = random.random() + 0.1
- pygame.init()
- screen = pygame.display.set_mode((450, 800), 0, 32)
- pygame.display.set_caption("天空,超爱你!")
- # 加载相关图像
- 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.x1, b.y1))
- screen.blit(b.image, (b.x2, b.y2))
- screen.blit(b.image, (b.x3, b.y3))
- # 敌机开始运动
- 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()
复制代码 |
|