关于精灵模块
代码中的游戏主循环方法的self.bullets.update()为什么可以直接调用 Bullet模块的update()方法,鱼油们棒棒忙import sys
import pygame
from set_up import Set_up
from ship import Ship
from bullet import Bullet
class Flank_flre:
"""管理侧面射击的类"""
def __init__(self):
"""初始化游戏并创建游戏资源"""
pygame.init()
#实例化用于储存设置的类
self.set = Set_up()
self.screen = pygame.display.set_mode((self.set.screen_width,
self.set.screen_height))
#设置窗口标题
pygame.display.set_caption("侧面射击")
self.ship = Ship(self)
#创建一个用于保存和管理精灵的容器类
self.bullets = pygame.sprite.Group()
def run_game(self):
"""游戏主循环"""
while True:
self._event_()
self.ship.update()
self.bullets.update()
self._dra_screen()
def _event_(self):
"""响应键盘和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._event_down(event)
elif event.type == pygame.KEYUP:
self._event_up(event)
def _event_down(self,event):
"""响应键盘按下事件"""
if event.key == pygame.K_UP:
self.ship.moving_top = True
elif event.key == pygame.K_DOWN:
self.ship.moving_bottom = True
elif event.key == pygame.K_SPACE:
self._file_bullet()
def _event_up(self,event):
"""响应键盘松开事件"""
if event.key == pygame.K_UP:
self.ship.moving_top = False
elif event.key == pygame.K_DOWN:
self.ship.moving_bottom = False
def _file_bullet(self):
"""创建一颗子弹"""
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _dra_screen(self):
#每次循环重新绘制屏幕
self.screen.fill(self.set.screen_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
#让最近绘制的屏幕可见
pygame.display.flip()
if __name__ == '__main__':
game = Flank_flre()
game.run_game()
______________________
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""管理飞船发射子弹的类"""
def __init__(self,game):
super().__init__()
self.screen = game.screen
self.set = game.set
self.color = self.set.bullet_color
#在(0,0)处创建一个子弹的矩形,在设置正确位置
self.rect = pygame.Rect(0,0,self.set.bullet_width,
self.set.bullet_height)
self.rect.midright = game.ship.rect.midright
self.x = float(self.rect.x)
def update(self):
#向右移动子弹
self.x += self.set.bullet_speed
#更新表示子弹的rect位置
self.rect.x = self.x
def draw_bullet(self):
"""在屏幕上绘制子弹"""
pygame.draw.rect(self.screen,self.color,self.rect)
页:
[1]