- 帖子
- 3
- 精华
- 0
- 积分
- 20
- 阅读权限
- 10
- 注册时间
- 2017-3-9
- 最后登录
- 2017-3-31
|
- import pygame
- from sys import exit
- import random
- def hit(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
- class Plane(object):
- def __init__(self):
- self.image = pygame.image.load('plane.png').convert_alpha()
- self.width = self.image.get_width()
- self.height = self.image.get_height()
- self.x = 225 - self.width / 2
- self.y = 700 - self.height / 2
- def move(self):
- mouseX, mouseY = pygame.mouse.get_pos()
- self.x = mouseX - self.width / 2
- self.y = mouseY - self.height / 2
- class Enemy:
- def restart(self):
- self.x = random.randint(50, 400)
- self.y = random.randint(-200, -50)
- self.speed = 0.3
- def __init__(self):
- self.restart()
- self.image = pygame.image.load('diji.png').convert_alpha()
- def move(self):
- if self.y < 800:
- self.y += self.speed
- else:
- self.restart()
- class Bullet:
- def __init__(self):
- self.x=0
- self.y=-5
- self.image=pygame.image.load('1.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
-
- pygame.init()
- screen=pygame.display.set_mode((450,800),0,32)
- pygame.display.set_caption('hello,world')
- background1=pygame.image.load('back.jpg').convert()
- pygame.mouse.set_visible(False)
- filename='yinyue.mp3'
- pygame.mixer.init()
- pygame.mixer.music.load(filename)
- pygame.mixer.music.play(1)
- enemy=Enemy()
- plane=Plane()
- bullets = []
- for i in range(5):
- bullets.append(Bullet())
- count_b = len(bullets)
- index_b = 0
- interval_b = 0
- enemies = []
- #向list中添加5架敌机
- for i in range(5):
- enemies.append(Enemy())
- while True:
- for event in pygame.event.get():
- if event.type==pygame.QUIT:
- pygame.quit()
- exit()
- screen.blit(background1,(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))
- for b in bullets:
- if b.active:
- for e in enemies:
- hit(e, b)
- b.move()
- screen.blit(b.image, (b.x, b.y))
- plane.move()
- for e in enemies:
- e.move()
- screen.blit(e.image, (e.x, e.y))
-
-
- enemy.move()
- screen.blit(enemy.image,(enemy.x,enemy.y))
-
- screen.blit(plane.image, (plane.x, plane.y))
- pygame.display.update()
-
复制代码 |
|