用pygame实现打飞机游戏-4-将飞机面向对象
1 #coding=utf-8 2 import pygame 3 #导入pygame模块 4 from pygame.locals import * 5 #导入检测键盘的子模块 6 class AircraftCoordinate(object): 7 def __init__(self): 8 #设置飞机默认的位置 9 self.x = 250 10 self.y = 600 11 self.screen =screen 12 #设置要显示的内容的窗口 13 self.imagePath = "./feiji/hero.gif" 14 self.aircraftImageFile = pygame.image.load(self.imagePath).convert() 15 def display(self): 16 # 17 screen.blit(self.aircraftImageFile,(self.x,self.y)) 18 def moveLeft(self): 19 self.x -= 20 20 def moveRight(self): 21 self.x += 20 22 def moveUp(self): 23 self.y -= 20 24 def moveDown(self): 25 self.y += 20 26 def shoot(self): 27 pass 28 if __name__ == '__main__': 29 #__name__变量,判断该模块是作为脚本被执行,还是被调用,当直接执行的时候,就是main,在被别人调用的时候,就是name 30 screen = pygame.display.set_mode((480,980),0,32) 31 #设置屏幕,0,32是默认值 32 bgImageFile = './feiji/background.png' 33 #导入图片 34 background = pygame.image.load(bgImageFile).convert() 35 #背景用background保存 36 aircraft = AircraftCoordinate() 37 #aircraftImageFile = './feiji/hero.gif' 38 #导入飞机图片 39 #aircraft = pygame.image.load(aircraftImageFile).convert() 40 #飞机图用aircraft保存 41 42 while True: 43 screen.blit(background,(0,0)) 44 #设置背景在屏幕的坐标,0.0是左上角的坐标。 45 #screen.blit(aircraft,(x,y)) 46 #设置飞机在屏幕的坐标 47 48 aircraft.display() 49 for event in pygame.event.get(): 50 #在发生的事件当中循环,意思可以等同于获取所有的键盘操作 51 if event.type == QUIT: 52 #判断是否是按下了关闭键 53 print("exit") 54 exit() 55 #退出程序 56 elif event.type ==KEYDOWN: 57 #判断是否按下了按键 58 if event.key == K_a or event.key == K_LEFT: 59 #判断是否按下了a键或者左键 60 print('左') 61 aircraft.moveLeft() 62 elif event.key == K_d or event.key == K_RIGHT: 63 #判断是否按下了d键或者右键 64 print('右') 65 aircraft.moveRight() 66 elif event.key == K_w or event.key == K_UP: 67 #判断是否按下了w键或者上键 68 print('上') 69 aircraft.moveUp() 70 elif event.key == K_s or event.key == K_DOWN: 71 #判断是否按下了s键或者下键 72 print('下') 73 aircraft.moveDown() 74 elif event.key == K_SPACE: 75 #判断是否按下了空格键 76 print('射子弹') 77 aircraft.shoot() 78 79 pygame.display.update() 80 #更新屏幕
www.wzxdm.com