
import math
import random
import pygame
import sys# pygame初始化
pygame.init()# 得分初始化
score = 0# 创建surface主窗体
screen = pygame.display.set_mode((1061, 658))
pygame.display.set_caption('planeGame 1.0 author:Keven Duan') # 给主窗体命名# 添加背景音乐
pygame.mixer.music.load('bg.mp3')
pygame.mixer.music.play(-1)
baopo = pygame.mixer.Sound("baopo.mp3")# 导入素材图片
icon = pygame.image.load('planeicon.png')
bg = pygame.image.load("background.png")
plane = pygame.image.load("plane.png")
gameover_img = pygame.image.load('gameover.png')
new_gameover = pygame.transform.scale(gameover_img, (500, 500)) # 调整图片大小
pygame.display.set_icon(icon) # 设置图标# 坐标的设置
#plane
planeX = 435
planeY = 450
planeStep = 0 # 飞机移动的参数# 创建ufo类
class UFO():def __init__(self):self.img = pygame.image.load("ufo.png")self.x = random.randint(0, 800)self.y = random.randint(0, 200)self.step = 0.1*random.randint(5, 20)def reset(self): # 重新加载坐标点self.x = random.randint(0, 800)self.y = random.randint(0, 200)# 创建子弹类
class Bulltet():def __init__(self):self.img = pygame.image.load("bullet.png")self.x = planeX + 65self.y = planeY - 10self.step = 1def hit(self):for u in ufo_list:if distance(u.x, u.y, self.x, self.y) < 30:global scorescore += 1baopo.play()bulltets.remove(self)u.reset()bulltets = []# 创建UFO对象
ufo_list=[]
def create_ufo():ufo_num = 8for i in range(ufo_num):ufo_list.append(UFO())
create_ufo()# 两点之间距离
def distance(ux ,uy, bx, by):a = bx - uxb = by - uyreturn math.sqrt(a * a + b * b)# 子弹的移动
def show_belltet():for b in bulltets:screen.blit(b.img, (b.x, b.y))b.y -= b.stepb.hit() # 每次显示判断是否击中if b.y < 0:bulltets.remove(b)# 飞机的移动与添加
def plane_move():global planeX# 控制飞机横坐标planeX -= planeStep# 防止飞机出界if planeX > 880:planeX = 880gameover()if planeX < 0:planeX = 0gameover()screen.blit(plane, (planeX, planeY)) # 添加飞机# ufo移动与添加
def ufo_move():global ufo_listfor e in ufo_list:screen.blit(e.img, (e.x, e.y)) # 添加ufoe.x += e.step# ufo 循环运动if e.x < 0:e.step *= -1e.y += 30elif e.x > 880:e.step *= -1e.y += 30elif e.y > planeY:gameover()ufo_list = []create_ufo()# 游戏失败画面
def gameover():"""游戏结束界面:param planeX: 飞机的横坐标:return: None"""global score, ufo_listscreen.blit(new_gameover, (290, 100))score = 0# 循环游戏体
while True:screen.blit(bg, (0, 0)) #添加背景图# 创建文字对象ft = pygame.font.SysFont(['方正粗黑宋简体', 'microsoftsansserif'], 40)text = ft.render(f"score:{score}", True, (0, 255, 0))screen.blit(text, (10, 10))for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:planeStep = 3elif event.key == pygame.K_RIGHT:planeStep = -3elif event.key == pygame.K_SPACE:# 添加子弹到列表bulltets.append(Bulltet())if score == 100:score = 1000ufo_move() # ufo的添加与移动plane_move() # 飞机的添加与移动show_belltet() # 显示子弹# 刷新界面pygame.display.update()
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!