飞机大战小游戏,这里需要下载pygame模块 这是需要的素材,需要的自取: 上代码:
import time
import pygame
from pygame.locals import *
import sys
import random
class Player():
def __init__(self,screen):
self.screen=screen
self.x=150
self.y=500
self.img=pygame.image.load(r"feiji/hero1.png")
self.BulletList=[]
self.moveLeftState=0
self.moveRightState=0
def display(self):
self.screen.blit(self.img,(self.x,self.y))
for b in self.BulletList:
b.display()
b.move()
if b.y<0:
self.BulletList.remove(b)
def move(self):
if self.moveLeftState==1 and self.x>-55:
self.x-=5
if self.moveRightState==1 and self.x<250:
self.x+=5
def fire(self):
b=PlayerBullet(self.screen,self.x,self.y)
self.BulletList.append(b)
class PlayerBullet():
def __init__(self,screen,x,y):
self.screen=screen
self.x=x+35
self.y=y-35
self.img=pygame.image.load(r"feiji/bullet.png")
def display(self):
self.screen.blit(self.img,(self.x,self.y))
def move(self):
self.y-=20
class Emeny():
def __init__(self,screen):
self.screen=screen
self.x=0
self.y=0
self.img=pygame.image.load(r"feiji/enemy0.png")
self.BulletList=[]
self.moveState=1
def display(self):
self.screen.blit(self.img,(self.x,self.y))
for b in self.BulletList:
b.display()
b.move()
if b.y>=600:
self.BulletList.remove(b)
def move(self):
if self.moveState==1:
self.x+=5
elif self.moveState==0:
self.x-=5
if self.x<-30:
self.moveState=1
elif self.x>285:
self.moveState=0
def fire(self):
b=EmenyBullet(self.screen,self.x,self.y)
self.BulletList.append(b)
class EmenyBullet():
def __init__(self,screen,x,y):
self.screen=screen
self.x=x+23
self.y=y+35
self.img=pygame.image.load(r"feiji/bullet2.png")
def display(self):
self.screen.blit(self.img,(self.x,self.y))
def move(self):
self.y+=20
def key_control(player):
for event in pygame.event.get():
if event.type==QUIT:
print("正在退出.....")
sys.exit(0)
elif event.type==KEYDOWN:
if event.key==K_LEFT:
print("玩家向左!")
player.moveLeftState=1
if event.key==K_RIGHT:
print("玩家向右!")
player.moveRightState=1
if event.key==K_SPACE:
print("玩家开火!")
player.fire()
elif event.type==KEYUP:
if event.key==K_LEFT:
print("停止向左...")
player.moveLeftState=0
if event.key==K_RIGHT:
print("停止向右...")
player.moveRightState=0
class main():
screen=pygame.display.set_mode((300,600))
background=pygame.image.load(r"feiji/background.png")
player=Player(screen)
emeny=Emeny(screen)
while 1==1:
screen.blit(background,(0,0))
player.display()
emeny.display()
emeny.move()
player.move()
r=random.randint(1,15)
if r==8:
emeny.fire()
key_control(player)
pygame.display.update()
time.sleep(0.05)
if __name__ == '__main__':
main()
|