你如果不想学习,那你也复制去玩玩吧。
import random
import pygame
from pygame.locals import *
import time
class HeroPlane:
'''定义玩家(英雄)'''
def __init__(self,screen_temp):
self.x = 300
self.y = 650
self.screen = screen_temp
self.image = pygame.image.load("./images/play1.png")
self.bullet_list = [] # 玩家子弹列表
def display(self):
'''绘制玩家飞机'''
self.screen.blit(self.image, (self.x,self.y))
# 绘制子弹
for b in self.bullet_list:
b.display()
if b.move():
self.bullet_list.remove(b)
def move_left(self):
'''向左移动'''
self.x -= 10
if self.x <= -30:
self.x = -30
def move_right(self):
'''向左移动'''
self.x += 10
if self.x >= 580:
self.x = 580
def fire(self):
'''发射子弹'''
self.bullet_list.append(Bullet(self.screen,self.x,self.y))
class Bullet:
'''定义子弹类'''
def __init__(self,screen_temp,x,y):
self.x = x+95
self.y = y
self.screen = screen_temp
self.image = pygame.image.load("./images/zd2.png")
def display(self):
'''绘制子弹'''
self.screen.blit(self.image, (self.x,self.y))
def move(self):
'''子弹在不停向上走'''
self.y -= 10
# 出界之后的子弹弹出列表
if self.y<= -15:
return True
class EnemyPlane:
'''定义敌机类'''
def __init__(self,screen_temp):
self.x = random.choice(range(650))
self.y = random.choice(range(10))
self.screen = screen_temp
self.image = pygame.image.load("./images/e1.png")
def display(self):
'''绘制敌机'''
self.screen.blit(self.image, (self.x,self.y))
def move(self,hero):
# 敌机一直向下走
self.y += 5
# 判断是否被子弹击中
for bullet in hero.bullet_list:
if bullet.x > self.x + 30 and bullet.x < self.x + 70 and bullet.y > self.y + 30 and bullet.y < self.y + 70:
return True
def key_control(hero_temp):
'''键盘控制'''
# 执行退出操作
for event in pygame.event.get():
if event.type ==QUIT:
print("exit!")
exit()
# 获取键盘按键
pressed_keys = pygame.key.get_pressed() #很多按键,1表示被按
#print(pressed_keys)
if pressed_keys[K_LEFT] or pressed_keys[K_a]:
# print("Left")
hero_temp.move_left()
elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
# print("Right....")
hero_temp.move_right()
if pressed_keys[K_SPACE]:
# print("space....")
hero_temp.fire()
def main():
'''主函数'''
# 创建游戏窗口,返回窗口对象
screen = pygame.display.set_mode((750,850),0,0) #右边x变正,下边y变正
# 创建一个游戏背景
background = pygame.image.load("./images/bg1.jpg")
# 创建玩家飞机
hero = HeroPlane(screen)
m = -484
emeny_list = []
while True:
# 绘制画面
screen.blit(background,(0,m))
m+=3
if m>= -183:
m=-484
# 绘制玩家飞机
hero.display()
# 键盘控制
key_control(hero)
# 随机绘制敌机
if random.choice(range(50)) == 10:
emeny_list.append(EnemyPlane(screen))
for emeny in emeny_list:
emeny.display()
if emeny.move(hero):
emeny_list.remove(emeny)
# 更新显示
pygame.display.update()
# 定时显示
time.sleep(0.04)
if __name__ =="__main__":
main()