关于python:自己弄的python小游戏turtle实现海龟赛跑

8次阅读

共计 1265 个字符,预计需要花费 4 分钟才能阅读完成。


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

咱们总共有 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. 游戏完结。这阐明咱们是赢了还是输了较量。

好了~~~

正文完
 0