- 帖子
- 12
- 精华
- 0
- 积分
- 63
- 阅读权限
- 20
- 注册时间
- 2013-9-11
- 最后登录
- 2013-10-3
|
感觉让Bullet类自己管理实例的状态的也不错- # -*- coding: utf-8 -*-
- import pygame,sys,random
- 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 Bullet:
- active_bullets = []
- bullets = []
- def __init__(self):
- self.x = 0
- self.y = -1
- self.image = pygame.image.load('bullet.png').convert_alpha()
- self.active = False
- Bullet.bullets.append(self)
- print(len(Bullet.bullets))
- def move(self):
- if self.y < 0:
- Bullet.active_bullets.pop(Bullet.active_bullets.index(self))
- Bullet.bullets.append(self)
- if self in Bullet.active_bullets:
- self.y -= 3
- 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
- Bullet.active_bullets.append(self)
- pygame.init()
- screen = pygame.display.set_mode((450,800),0,32)
- pygame.display.set_caption("Hello,Wrold!")
- background = pygame.image.load('back.jpg').convert()
- plane = pygame.image.load('plane.png').convert_alpha()
- for i in range(5):
- Bullet()
- enemy = Enemy()
- interval_b = 0
- while True:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- sys.exit()
- screen.blit(background,(0,0))
- interval_b -= 1
- if interval_b < 0:
- if len(Bullet.bullets):
- Bullet.bullets.pop(0).restart()
- interval_b = 100
- for b in Bullet.active_bullets:
- 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()
复制代码 |
|