打飞机代码:玩家飞机发射子弹
import pygame
from pygame.locals import *
'''
5. 实现玩家飞机发射子弹
接下来要做的任务:
1. 实现飞机在你想要的位置显示
2. 实现按键控制飞机移动
3. 实现按下空格键的时候,显示一颗子弹
'''
class HeroPlane(object):
def __init__(self,screen):
self.x = 230
self.y = 700
self.screen = screen
self.imageName = "./feiji/hero1.png"
self.image = pygame.image.load(self.imageName).convert()
self.bulletList = []
def display(self):
self.screen.blit(self.image,(self.x,self.y))
for bullet in self.bulletList:
bullet.display()
bullet.move()
def moveLeft(self):
self.x -= 10
def moveRight(self):
self.x += 10
def sheBullet(self):
newBullet = Bullet(self.x, self.y, self.screen)
self.bulletList.append(newBullet)
class Bullet(object):
def __init__(self,x,y,screen):
self.x = x+40
self.y = y-20
self.screen = screen
self.image = pygame.image.load("./feiji/bullet.png").convert()
def move(self):
self.y -= 5
def display(self):
self.screen.blit(self.image,(self.x,self.y))
def key_control(heroPlane):
for event in pygame.event.get():
if event.type == QUIT:
print("exit")
exit()
elif event.type == KEYDOWN:
if event.key == K_a or event.key == K_LEFT:
print('left')
heroPlane.moveLeft()
elif event.key == K_d or event.key == K_RIGHT:
print('right')
heroPlane.moveRight()
elif event.key == K_SPACE:
print('space')
heroPlane.sheBullet()
def main():
screen = pygame.display.set_mode((480,852),0,32)
background = pygame.image.load("./feiji/background.png").convert()
heroPlane = HeroPlane(screen)
while True:
screen.blit(background,(0,0))
heroPlane.display()
key_control(heroPlane)
pygame.display.update()
if __name__ == "__main__":
main()