英雄机子弹是否越界、敌机子弹是否越界、子弹产生
import pygame # pygame2d游戏 import time from pygame.locals import * import random class HeroPlane(object): def __init__(self,screen_temp): self.x=210 self.y=700 self.screen=screen_temp self.image= pygame.image.load("./feiji/hero1.png") self.bullet_list=[] def display(self): self.screen.blit(self.image, (self.x, self.y)) for bullet in self.bullet_list: bullet.display() bullet.move() if bullet.judge():#判断子弹是否越界 self.bullet_list.remove(bullet) def move_left(self): self.x-=5 def move_right(self): self.x+=5 def fire(self): self.bullet_list.append(Bullet(self.screen,self.x,self.y)) class EnemyPlane(object): def __init__(self,screen_temp): self.x=0 self.y=0 self.screen=screen_temp#显示敌机 self.image= pygame.image.load("./feiji/enemy0.png") self.bullet_list=[] self.direction="right"#飞机默认的显示方向 def display(self): self.screen.blit(self.image, (self.x, self.y)) for bullet in self.bullet_list: bullet.display() bullet.move() if bullet.judge(): # 判断敌机子弹是否越界 self.bullet_list.remove(bullet) def move(self): if self.direction=="right":#控制方向 self.x+=5 elif self.direction=="left": self.x-=5 if self.x>480-50:#测试距离 self.direction="left" elif self.x<0:#往右 self.direction="right" def fire(self):#敌机子弹1 random_num=random.randint(1,100) if random_num==8 or random_num==57:#random生成随机数 self.bullet_list.append(EnemyBullet(self.screen,self.x,self.y))#敌机当前位置传过去 class Bullet(object): def __init__(self,screen_temp,x,y): self.x = x+40 self.y = y-20 self.screen = screen_temp self.image = pygame.image.load("./feiji/bullet.png") def display(self): self.screen.blit(self.image,(self.x,self.y)) def move(self): self.y-=20 def judge(self): if self.y<0: return True#一定越界 else: return False#没越界 class EnemyBullet(object):#敌机子弹2 def __init__(self,screen_temp,x,y): self.x = x self.y = y self.screen = screen_temp self.image = pygame.image.load("./feiji/bullet1.png") def display(self): self.screen.blit(self.image,(self.x,self.y)) def move(self): self.y+=5 def judge(self): if self.y>852:#超过这个距离就消失 return True#一定越界 else: return False#没越界 def key_control(herotemp): for event in pygame.event.get(): # 11 if event.type == QUIT: # 按下叉号 print("exit") exit() # 退出程序,循环结束是break elif event.type == KEYDOWN: # 按下键盘键 if event.key == K_a or event.key == K_LEFT: print("left") herotemp.move_left() elif event.key == K_d or event.key == K_RIGHT: print("right") herotemp.move_right() elif event.key == K_SPACE: print("space") herotemp.fire() def main(): # 01 screen = pygame.display.set_mode((480, 852), 0, 32) # 1窗口 background = pygame.image.load("./feiji/background.png") # 2背景 hero = HeroPlane(screen) enemy=EnemyPlane(screen) while True: # 5死循环,一直重复 screen.blit(background, (0, 0)) # 3背景贴到窗口00处 hero.display() enemy.display() enemy.move()#调用敌机方法 enemy.fire() pygame.display.update() # 4显示贴的效果 key_control(hero) time.sleep(0.01) # 6电脑配置不高的话,内存占用会很大,所以延时显示可以减少内存消耗 if __name__ == '__main__': # 0 main()