一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

用python实现海龟赛跑小游戏代码示例

时间:2022-01-13 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下用python实现海龟赛跑小游戏代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

代码说明

导入包

from turtle import Turtle, Screen
import random

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

screen = Screen()
screen.setup(, )

有一个名为 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. 比赛结束。这说明我们是赢了还是输了比赛。

热门栏目