LHL Python 飞机大战 v0.0.1
作者:互联网
飞机大战
待更新
import pygame
import random
import math
# 初始化
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('LHL\'S船新版本飞机大战')
icon = pygame.image.load('ufo.jpg')
pygame.display.set_icon(icon)
bgImg = pygame.image.load('bj.jpg')
# 游戏结束
is_over = False
# 音效
pygame.mixer.music.load('bg.mp3')
#pygame.mixer.music.play(-1)
# 分数
score = 0
font = pygame.font.Font('freesansbold.ttf', 32)
def show_score():
text = f"Score:{score}"
score_render = font.render(text, True, (0, 21, 42))
screen.blit(score_render, (10, 10))
over_font = pygame.font.Font('freesansbold.ttf', 32)
def check_is_over():
if is_over:
text = "GAMA OVER"
render = over_font.render(text, True, (255, 21, 42))
screen.blit(render, (300, 200))
# 飞机
playImg = pygame.image.load('play2.png')
playerX = 400
playerY = 500
playerStep = 0 # 玩家移动速度
# 敌人
number_of_enemies = 6
class Bullet():
def __init__(self):
self.img = pygame.image.load('bullet3.png')
self.x = playerX + 20
self.y = playerY - 90
self.step = 2
def hit(self):
global score
for e in enemies:
if distance(self.x, self.y, e.x, e.y) < 60:
bullets.remove(self)
e.reset()
score += 1
print(score)
bullets = []
class Enemy():
def __init__(self):
self.img = pygame.image.load('emery.png')
self.x = random.randint(200, 600)
self.y = random.randint(50, 250)
self.step = random.randint(1, 3)
def reset(self):
self.x = random.randint(200, 600)
self.y = random.randint(50, 250)
enemies = [] # 保存敌人
for i in range(number_of_enemies):
enemies.append(Enemy())
enemyImg = pygame.image.load('emery.png')
enemyStep = 1
enemyX = random.randint(200, 600)
enemyY = random.randint(50, 300)
# 计算距离
def distance(bx, by, ex, ey):
a = bx - ex
b = by - ey
return math.sqrt(a * a + b * b)
def show_enemy():
global is_over
global playerY, playerX
for e in enemies:
screen.blit(e.img, (e.x, e.y))
e.x += e.step
if e.x > 700 or e.x < 0:
e.step *= -1
e.y += 40
if e.y > 450:
is_over = True
print("游戏结束!")
enemies.clear()
def move_player():
# x轴移动
global playerX, enemyStep, enemyY
playerX += playerStep
if playerX >= 700:
playerX = 700
if playerX <= 0:
playerX = 0
# 防止飞机出界
if playerX >= 700:
playerX = 700
if playerX <= 0:
playerX = 0
def show_bullets():
for b in bullets:
screen.blit(b.img, (b.x, b.y))
b.hit()
b.y -= b.step
if b.y < 0:
bullets.remove(b)
# 主循环
running = True
while running:
screen.blit(bgImg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 如果是键盘按下
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
playerStep = 2
elif event.key == pygame.K_LEFT:
playerStep = -2
elif event.key == pygame.K_SPACE:
bullets.append(Bullet())
# 键盘抬起
if event.type == pygame.KEYUP:
playerStep = 0
screen.blit(playImg, (playerX, playerY))
move_player()
show_score()
show_enemy()
show_bullets()
check_is_over()
pygame.display.update()
标签:random,Python,self,LHL,score,pygame,playerX,v0.0,def 来源: https://blog.csdn.net/Simple_questions/article/details/105356544