如何为Python Turtle Race实现完善的平局决胜机制?
优化Turtle Race平局判断逻辑
原代码存在的问题
- 仅用
win和lose两个布尔变量无法记录多个平局获胜者,只能处理用户猜中其中一个的情况 - 结果判断逻辑嵌套在循环内部,会导致重复输出,且存在缩进错误(如
turtle.forward()不在for循环内,只有最后一只乌龟移动) - 平局场景下未猜中任何获胜者时,无法正确展示所有平局者信息
修正后的代码
from turtle import Turtle, Screen import random is_race_on = False screen = Screen() screen.setup(500, 400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ") colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] y_positions = [-125, -75, -25, 25, 75, 125] all_turtles = [] # 创建所有参赛乌龟 for turtle_index in range(0, 6): new_turtle = Turtle() new_turtle.color(colors[turtle_index]) new_turtle.penup() new_turtle.shape("turtle") new_turtle.goto(x=-230, y=y_positions[turtle_index]) all_turtles.append(new_turtle) winning_colors = [] # 用列表存储所有获胜者颜色 if user_bet: is_race_on = True while is_race_on: for turtle in all_turtles: # 每只乌龟每次循环随机前进 random_distance = random.randint(0, 10) turtle.forward(random_distance) # 判断是否到达终点 if turtle.xcor() > 230: winning_colors.append(turtle.pencolor()) is_race_on = False # 触发比赛结束 # 比赛结束后统一处理结果输出 if len(winning_colors) > 1: # 平局场景 winners_str = ", ".join(winning_colors) print(f"There was a tie between {winners_str}!") if user_bet in winning_colors: print(f"You've Won!! Your bet {user_bet} is one of the winners!") else: print(f"You lost. The winners are {winners_str}.") else: # 单胜者场景 winner = winning_colors[0] if user_bet == winner: print(f"You've Won!! The {winner} turtle is the winner!") else: print(f"You lost! The {winner} turtle is the winner!!") screen.exitonclick()
关键改进点
- 使用**列表
winning_colors**存储所有到达终点的乌龟颜色,支持任意数量的平局者 - 将结果判断逻辑移到比赛结束后(
while循环外),避免重复输出,逻辑更清晰 - 修正缩进错误,确保每只乌龟在每次循环中都会前进
- 完善平局场景下的输出:无论用户是否猜中,都会展示所有获胜者信息,同时明确告知用户输赢状态
内容的提问来源于stack exchange,提问作者Cameron
相关产品推荐
相关产品推荐

