简体   繁体   English

如何修复Python中的无限循环-Turtle Graphics

[英]How to fix infinite loop in Python - turtle graphics

I am trying to code a program that allows the user to choose out of several options of a scene to draw. 我正在尝试编写一个程序,该程序允许用户从要绘制的场景的多个选项中进行选择。 I come to an issue with drawing the sun. 我在画太阳时遇到了一个问题。 When I run the program the sun wont stop drawing and fill in the color. 当我运行程序时,太阳不会停止绘制并填充颜色。 Everything else works. 其他一切正常。

import turtle
import random
t = turtle.Turtle()
turtle.setup(800,600)

def draw_sunshine():
    t.penup()
    t.goto(350,250)
    t.pendown()
    t.color('black', 'yellow')
    t.speed(9)
    t.begin_fill()
    while True:
        t.forward(100)
        t.left(170)
        t.right(100)
        if abs(t.pos()) < 1:
            break
    t.end_fill()
    t.done()

weather = False
while weather == False:
    weather = input("Would you like to draw rain or sunshine? ")
    if weather == "rain":
        draw_rain()
    else:
        draw_sunshine()

The problem is likely this termination test: 问题可能是此终止测试:

if abs(t.pos()) < 1:
    break

The pos() method returns a pair of numbers, eg (0.0, 0.0), as a turtle.Vec2D type, which abs() only operates on the first, x . pos()方法以turtle.Vec2D类型返回一对数字,例如( turtle.Vec2D ,而abs()仅对第一个x进行运算。 In this situation, x will never be less than 1 as that's near the center of the screen and we're far off to the right. 在这种情况下, x永远不会小于1,因为它位于屏幕中心附近,而我们离右边很远。

Below is a different approach where we control the loop based on the number of iterations it will take to complete the drawing of the sun. 下面是一种不同的方法,其中我们根据完成太阳绘制所需的迭代次数来控制循环。 To make this work, I've adjusted the sun drawing to finish in a reasonable (integral) number of iterations and still fill with color nicely: 为了完成这项工作,我已经调整了sun绘图,使其以合理(完整)的迭代次数完成,并且仍然很好地填充了颜色:

from turtle import Turtle, Screen

def draw_sunshine(turtle):
    turtle.penup()
    turtle.goto(350, 250)
    turtle.pendown()
    turtle.color('black', 'yellow')
    turtle.speed("fast")

    turtle.begin_fill()

    for _ in range(24):
        turtle.forward(100)
        turtle.left(75)

    turtle.end_fill()

screen = Screen()
screen.setup(800, 600)

yertle = Turtle()

weather = ''

while not weather:
    weather = input("Would you like to draw 'rain' or 'sunshine'? ")

    if weather == "rain":
        draw_rain(yertle)
    else:
        draw_sunshine(yertle)

yertle.hideturtle()
screen.exitonclick()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM