一、安装Pygame
地址: https://mirrors.aliyun.com/pypi/simple
二、编写代码(完整代码)
import pygame
import random
import math
#1.初始化界面
pygame.init()
screen=pygame.display.set_mode((800,600))
pygame.display.set_caption('飞机大战')
icon=pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
bgImg=pygame.image.load('bg.png')
pygame.mixer.music.load('bg.wav')
pygame.mixer.music.play(-1)
bao_sound=pygame.mixer.Sound('exp.wav')
score=0
font=pygame.font.Font('ARLRDBD.TTF',32)
def show_score():
text=f"Score:{score}"
score_render=font.render(text,True,(0,255,0))
screen.blit(score_render,(10,10))
is_over=False
Over_font=pygame.font.Font('ARLRDBD.TTF',64)
def check_is_over():
if is_over:
text="Game Over"
render=Over_font.render(text,True,(255,0,0))
screen.blit(render,(240,250))
playerImg=pygame.image.load('player.png')
playerX=400
playerY=500
playerStep=0
number_of_enemies=6
class Enemy():
def __init__(self):
self.img=pygame.image.load('enemy.png')
self.x=random.randint(200,600)
self.y=random.randint(50,250)
self.step=random.randint(2,6)
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())
def distance(bx,by,ex,ey):
a=bx-ex
b=by-ey
return math.sqrt(a*a+b*b)
class Bullet():
def __init__(self):
self.img = pygame.image.load('bullet.png')
self.x = playerX+16
self.y = playerY+10
self.step = 10
def hit(self):
global score
for e in enemies:
if(distance(self.x,self.y,e.x,e.y)<30):
bao_sound.play()
bullets.remove(self)
score+=1
e.reset()
print("击中了")
print(score)
bullets=[]
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)
def show_enemy():
global is_over
for e in enemies:
screen.blit(e.img,(e.x,e.y))
e.x+=e.step
if(e.x>736 or e.x<0):
e.step*=-1
e.y+=40
if e.y>450:
is_over=True
print("游戏结束!")
enemies.clear()
def move_player():
global playerX
playerX+=playerStep
if playerX>736:
playerX=736
if playerY<0:
playerX=0
#游戏主循环
running=True
while True:
screen.blit(bgImg,(0,0))
screen.blit(playerImg,(playerX,playerY))
show_enemy()
move_player()
show_bullets()
show_score()
check_is_over()
for event in pygame.event.get():
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_RIGHT:
playerStep=5
elif event.key==pygame.K_LEFT:
playerStep=-5
elif event.key==pygame.K_SPACE:
print('发射子弹....')
bullets.append(Bullet())
if event.type==pygame.KEYUP:
playerStep=0
if event.type == pygame.QUIT:
running = False
pygame.quit()
pygame.display.update()