import pgzrun
from pgzhelper import *
import random
WIDTH=500
HEIGHT=500
MyPlane=Actor('plane',(WIDTH/2, HEIGHT/2))
Enemies=[]
bullets=[]
game_over = False
def draw():
global Enemies, game_over
screen.clear()
MyPlane.draw()
for Enemy in Enemies:
Enemy.draw()
for bullet in bullets:
bullet.draw()
# 游戏结束弹窗
if game_over:
# 半透明遮罩层
screen.draw.filled_rect(
Rect(0, 0, WIDTH, HEIGHT),(0, 0, 0, 200) # RGBA最后一位是透明度(0-255)
)
screen.draw.text(
"GAME OVER",
center=(WIDTH//2, HEIGHT//2),
fontsize=60,
color="red",
gcolor="yellow" # 渐变颜色
)
def update():
global MyPlane,Enemies, game_over, bullets
if random.randint(1, 60) == 1:
spawn_enemy()
for Enemy in Enemies[:]:
Enemy.y += 1
if Enemy.top > HEIGHT:
Enemies.remove(Enemy)
shoot_bullet()
for bullet in bullets[:]:
bullet.y -= 5
if bullet.bottom < 0:
bullets.remove(bullet)
continue
collision_index = bullet.collidelist(Enemies)
if collision_index != -1:
Enemies.pop(collision_index)
bullets.remove(bullet)
if MyPlane.collidelist(Enemies)!=-1:
MyPlane.image='alien_hurt'
game_over=True
def on_mouse_move(pos):
MyPlane.pos = pos
MyPlane.left = max(MyPlane.left, 0)
MyPlane.right = min(MyPlane.right, WIDTH)
MyPlane.top = max(MyPlane.top, 0)
MyPlane.bottom = min(MyPlane.bottom, HEIGHT)
def spawn_enemy():
global Enemies
Enemy=Actor('enemy',(random.uniform(0,WIDTH),0))
Enemy.scale=0.05
Enemies.append(Enemy)
def shoot_bullet():
global bullets
bullet=Actor('bullet',MyPlane.pos)
bullet.scale=0.01
bullets.append(bullet)
pgzrun.go()