目录
  • 代码说明
  • 输出图像
  • 总结

废话不多说,直接开始拉~~~

我们总共有 6 只海龟,颜色不同,它们以随机长度移动。首先,我们应该通过输入乌龟的颜色来押注乌龟。第一个越线的乌龟被宣布为获胜者。整个代码是通过导入海龟和随机库在 python 中完成的。

代码说明

导入包

from turtle import turtle, screen
import random

random 函数用于生成距离(随机),由海龟移动。最好给出屏幕尺寸,因为我们很容易找到坐标并进行相应的更改。

screen = screen()
screen.setup(width=500, height=400)

有一个名为 textinput() 的函数,它会打开一个对话框并要求用户输入。

user_bet = screen.textinput(title="place your bet", prompt="which turtle will win the race? enter a color: ")

接下来,我们应该给我们的种族海龟颜色。所以,我们可以区分它们。以及然后应该代表比赛的坐标。

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-100, -60, -20, 20, 60, 100]

通过考虑上述 y 坐标和颜色,使用 for 循环对所有海龟的确切坐标进行分类。

for turtle_index in range(0,6):
    new_turtle = turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-230, y= y_positions[turtle_index])
    all_turtles.append(new_turtle)

现在,我们应该做的最后一件事是让我们的海龟每次移动一个随机距离。而最先到达屏幕另一端的乌龟就是赢得比赛的乌龟。一开始,我们对乌龟下注,如果乌龟赢了,我们就赢了,如果它输了,我们也输了。

while is_race_on:
    for turtle in all_turtles:
        if turtle.xcor() > 230:
            is_race_on = false
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print(f"you've won!, the {winning_color} turtle is the winner.")
            else:
                print(f"you've lost!, the {winning_color} turtle is the winner.")
        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

设置屏幕宽度和高度的主要优点是我们可以通过假设屏幕为方格纸轻松计算开始和结束坐标。

输出图像

a. 将“红色”作为用户输入。

b. 海龟如何移动的图像。

c. 比赛结束。这说明我们是赢了还是输了比赛。

总结

到此这篇关于用python实现海龟赛跑小游戏的文章就介绍到这了,更多相关python海龟赛跑内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!