打飞机代码:显示、控制玩具飞机-面向对象
import pygame
from pygame.locals import *
'''
4. 使用面向对象的方式显示飞机,以及控制其左右移动
练一下:接下来要做的任务:
1. 实现飞机在你想要的位置显示
2. 实现按键控制飞机移动
3. 实现按下空格键的时候,显示一颗子弹
'''
class HeroPlane(object):
def __init__(self,screen):
self.x = 230
self.y = 600
self.screen = screen
self.imageName = "./feiji/hero.gif"
self.image = pygame.image.load(self.imageName).convert()
self.bullet = []
def display(self):
self.screen.blit(self.image,(self.x,self.y))
def moveLeft(self):
self.x -= 10
def moveRight(self):
self.x += 10
def sheBullet(self):
pass
if __name__ == "__main__":
screen = pygame.display.set_mode((480,890),0,32)
background = pygame.image.load("./feiji/background.png").convert()
heroPlane = HeroPlane(screen)
while True:
screen.blit(background,(0,0))
heroPlane.display()
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')
pygame.display.update()