赞
踩
发射子弹
import sys # 用以退出程序 import pygame # import库 from pygame.sprite import Group bg_color = 230,230,230 class Ship: def __init__(self,screen): self.screen = screen self.image = pygame.image.load('images/ship.bmp').convert_alpha() self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.midbottom = self.screen_rect.midbottom self.moving_right = False self.center_x = float(self.rect.centerx) self.center_y = float(self.rect.centerx) self.ship_speed_factor = 5 self.bullets_allowed = 10 def blitme(self): self.screen.blit(self.image,self.rect) def update(self): if self.moving_right and self.rect.right < self.screen_rect.right: self.center_x += self.ship_speed_factor self.rect.centerx = self.center_x class Bullet(pygame.sprite.Sprite): def __init__(self,screen,ship): pygame.sprite.Sprite.__init__(self) self.screen = screen self.bullet_width = 3 self.bullet_height = 10 self.bullet_color = 6,60,160 self.speed_factor = 10 # 设置速度 self.rect = pygame.Rect(0, 0, self.bullet_width, self.bullet_height) # 定义左边为屏幕的左上角出现一个长宽固定的矩形 self.rect.top = ship.rect.top self.rect.centerx = ship.rect.centerx self.y = float(self.rect.y) def update(self): self.y -= self.speed_factor self.rect.centery = self.y def draw_bullet(self): pygame.draw.rect(self.screen,self.bullet_color,self.rect) def remove_bullet(bullets): for i in bullets.copy(): if i.rect.bottom <= 0: bullets.remove(i) def run_game(): pygame.init() # 初始化 screen = pygame.display.set_mode((1000, 800)) # 返回一个屏幕 此时出现一个窗口 pygame.display.set_caption("ship") # 设置窗口的标题 bullets = Group() flyboat = Ship(screen) while True: # 死循环 for event in pygame.event.get(): # 检测用户的键盘鼠标等输入 if event.type == pygame.QUIT: # 此处仅检测是否退出 sys.exit() # 退出 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: flyboat.moving_right = True elif event.key == pygame.K_SPACE: if len(bullets) < flyboat.bullets_allowed: new_bullet = Bullet(screen, flyboat) bullets.add(new_bullet) elif event.type == pygame.KEYUP: # key up if event.key == pygame.K_RIGHT: flyboat.moving_right = False screen.fill(bg_color) flyboat.blitme() for i in bullets: i.draw_bullet() i.update() remove_bullet(bullets) pygame.display.flip() # 绘制一个新屏幕 并擦去旧屏幕 以形成平滑移动 run_game()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。