[Python] 纯文本查看 复制代码 import turtle
import random
# 设置分数和游戏变量
score = 0
zombies = []
bullets = []
player_speed = 15
# 设置屏幕
wn = turtle.Screen()
wn.title("角色打僵尸游戏")
wn.bgcolor("lightblue")
wn.setup(width=800, height=600)
# 显示分数
score_display = turtle.Turtle()
score_display.speed(0)
score_display.color("black")
score_display.penup()
score_display.hideturtle()
score_display.goto(0, 260)
score_display.write("分数: 0", align="center", font=("Courier", 24, "normal"))
# 创建玩家角色
player = turtle.Turtle()
player.shape("triangle") # 玩家形状
player.color("blue")
player.penup()
player.goto(0, -250) # 玩家初始位置
# 创建僵尸
def create_zombie():
zombie = turtle.Turtle()
zombie.shape("square") # 僵尸形状
zombie.color("green")
zombie.penup()
zombie.goto(random.randint(-390, 390), random.randint(100, 290))
zombies.append(zombie)
# 更新分数
def update_score():
global score
score += 1
score_display.clear()
score_display.write("分数: {}".format(score), align="center", font=("Courier", 24, "normal"))
# 创建子弹
def create_bullet():
bullet = turtle.Turtle()
bullet.shape("circle")
bullet.color("red")
bullet.penup()
bullet.goto(player.xcor(), player.ycor() + 10) # 从玩家位置发射子弹
bullet.setheading(90) # 设置向上发射
bullets.append(bullet)
# 检查是否击中僵尸
def check_hit():
global zombies
for bullet in bullets:
for zombie in zombies:
if bullet.distance(zombie) < 20: # 设置撞击阈值
bullet.hideturtle() # 隐藏子弹
zombie.hideturtle() # 隐藏僵尸
bullets.remove(bullet) # 从子弹列表中移除
zombies.remove(zombie) # 从僵尸列表中移除
update_score() # 更新分数
break # 退出內层循环
# 移动玩家
def go_left():
x = player.xcor()
x -= player_speed
if x < -390: # 不让玩家超出屏幕左边界
x = -390
player.setx(x)
def go_right():
x = player.xcor()
x += player_speed
if x > 390: # 不让玩家超出屏幕右边界
x = 390
player.setx(x)
# 鼠标点击事件
def shoot(x, y):
create_bullet()
# 初始化僵尸
for _ in range(5):
create_zombie()
# 绑定键盘事件
wn.listen()
wn.onkey(go_left, "Left") # 左箭头键
wn.onkey(go_right, "Right") # 右箭头键
wn.onclick(shoot) # 鼠标点击事件
# 游戏主循环
while True:
# 移动子弹
for bullet in bullets:
bullet.forward(10)
# 检查子弹是否出界
if bullet.ycor() > 300:
bullet.hideturtle()
bullets.remove(bullet)
# 检查是否击中僵尸
check_hit()
# 生成新的僵尸
if len(zombies) < 5:
create_zombie()
wn.update() # 更新屏幕
wn.mainloop() |