自己弄的python小游戏,turtle实现海龟赛跑

879 阅读2分钟

image.png

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

我们总共有 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. 将“红色”作为用户输入。

image.png

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

image.png

C. 游戏结束,这说明我们是赢了还是输了比赛。

image.png

好了~~~