之前都是面向过程式编码,接下来我们将使用面向对象式编码来实现这个游戏。
实操     
代码:
import pygame
from pygame.locals import *
'''
1、实现飞机的显示,并且可以控制飞机的移动【面向对象】
'''
class HeroPlane(object):
def __init__(self,screen):
self.x=150
self.y=450
self.screen=screen
self.imageName='./背景/我方.png'
self.image=pygame.image.load(self.imageName)
pass
def moveleft(self):
if self.x>0:
self.x-=10
pass
def moveright(self):
if self.x<310:
self.x+=10
pass
def display(self):
self.screen.blit(self.image,(self.x,self.y))
pass
pass
def key_control(HeroPlane):
eventList = pygame.event.get()
for event in eventList:
if event.type == QUIT:
print('退出')
exit()
pass
elif event.type == KEYDOWN:
if event.type == K_a or event.key == K_LEFT:
print('left')
HeroPlane.moveleft()
pass
elif event.type == K_d or event.key == K_RIGHT:
print('right')
HeroPlane.moveright()
pass
elif event.key == K_SPACE:
print('K_SPACE')
pass
pass
def main():
screen=pygame.display.set_mode((350,500),depth=32)
background=pygame.image.load('./背景/背景图.jpg')
pygame.display.set_caption('飞机游戏')
pygame.mixer.init()
pygame.mixer.music.load('./背景/背景音乐.MP3')
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(-1)
hero=HeroPlane(screen)
while True:
screen.blit(background,(0,0))
hero.display()
key_control(hero)
pygame.display.update()
pass
if __name__=='__main__':
main()
|