Python海龟图形中的生命计数器

2024-04-20 11:03:21 发布

您现在位置:Python中文网/ 问答频道 /正文

关于如何用Python海龟图形制作生命计数器,我需要一些帮助

我的代码:

def draw_lives():

    global lives

    lives = turtle.Turtle()
    lives.penup
    lives.hideturtle
    lives.goto(-200, 400)

    while True:
        lives.write("Lives: " + str(lives), font=("Arial", 50, "normal"))
        if lives > 0:
        lives.write("You have lost all lives. Try again.", font=("Arial", 50, "normal"))
        break

我想让我的生活对抗一只乌龟,而不仅仅是某个地方的随机计数器(这听起来会更好)

此外,我的if lives > 0:错误是>Turtleint的实例之间不受支持

有人能帮忙吗


Tags: 代码图形ifdef计数器globalwrite海龟
2条回答

你的代码构造得很糟糕,让我们看看细节。主要问题是,对于计数器和显示计数器的海龟都使用相同的变量名lives。给他们起不同的名字。如果您这样做,您不需要:

global lives

下一个问题是基本Python:

lives.penup
lives.hideturtle

这些是方法调用,因此它们应该是:

lives.penup()
lives.hideturtle()

最后,您的while True:在这里没有业务,或者在海龟事件驱动程序中没有业务。在if语句中缺少一两行代码

让我们重新编写代码,以便它更新屏幕上lives计数器的值:

from turtle import Screen, Turtle

FONT = ("Arial", 24, "normal")

def draw_lives():
    lives_pen.clear()

    if lives > 0:
        lives_pen.write("Lives: " + str(lives), font=FONT)
    else:
        lives_pen.write("You have lost all lives. Try again.", font=FONT)

lives = 5

lives_pen = Turtle()  # this turtle is only used to update lives counter display
lives_pen.hideturtle()
lives_pen.penup()
lives_pen.goto(-200, 300)
lives_pen.write("Lives: " + str(lives), font=FONT)

if __name__ == '__main__':
    from time import sleep

    # test code

    screen = Screen()

    for _ in range(lives + 1):
        draw_lives()
        sleep(1)
        lives -= 1

    screen.exitonclick()

__main__部分只是测试代码,以确认draw_lives()的工作方式符合我们的要求

lives_pen这样的实用程序海龟应该只创建一次,而不是每次需要更新计数器时,因为它们是全局实体,并且在函数退出时不会被垃圾收集

It's a bad practice to use ^{} in your code.相反,您可以为海龟创建自定义属性

这非常简单,几乎没有什么不便:

from turtle import Turtle
pen = Turtle()
pen.lives = 5 # Here, the lives attribute is created

您甚至可以对字体执行相同的操作,但这可能是不必要的:

pen.font = ("Arial", 30, "normal")

如果失去生命是生命计数将被更新的唯一情况,不要在循环中不断重写它们 (当然,除非有东西挡住了文本,并且您希望文本显示在顶部), 只有在失去生命时才重写它

我们可以在如下函数中重新绘制更新生命:

def update_lives():
    pen.clear()
    if pen.lives:
        pen.write(f"Lives: {pen.lives}", font=pen.font)
    else:
        pen.write("You have lost all lives. Try again.", font=pen.font)
    pen.lives -= 1 # Remove this line and this becomes your typical text updater

为了看到这一点,我实现了一个演示,每当用户按下空格键时,就会失去一条生命:

from turtle import Turtle, Screen

wn = Screen()

def update_lives():
    pen.clear()
    if pen.lives:
        pen.write(f"Lives: {pen.lives}", font=pen.font)
    else:
        pen.write("You have lost all lives. Try again.", font=pen.font)
    pen.lives -= 1

pen = Turtle(visible=False)
pen.penup()
pen.goto(-300, 200)
pen.lives = 5
pen.font = ("Arial", 30, "normal")

update_lives()

wn.listen()
wn.onkey(update_lives, 'space')

使用上述代码,当用户到达0时,再次按空格将使函数继续显示负值

为了解决这个问题,对于主游戏循环,使用while pen.lives告诉python只保持循环,直到剩余的生命数大于0

while pen.lives:
    # Your game code here
    wn.update()

输出:

enter image description here

相关问题 更多 >