4.3节练习5-艾伦·唐尼(Allen Downey)的“ Think Python”

时间:2018-10-11 15:32:48

标签: python function turtle-graphics

可以在此处访问练习的链接-Case Study: Interface Design, Exercise Section 4.3

引用该问题,似乎我必须实现一个arc()函数:

  

制作更通用的circle版本,称为arc,该版本带有一个附加参数angle,该参数确定要绘制圆的比例。 angle以度为单位,因此,当angle = 360时,arc应该绘制一个完整的圆。

我到目前为止编写的代码:

import turtle
import math
bob = turtle.Turtle()

def polygon(t, n, length):
    for i in range(n):
        t.fd(length)
        t.lt(360/n)

def circle(t, r):
    circumference = 2 * math.pi * r
    n = int(circumference/3) + 1
    length = circumference/n
    polygon(t, n, length)

def arc(t, r, angle):
    arc_length = 2 * math.pi * r * (angle/360)
    n = (arc_length/4) + 1

arc(bob, 1000, 45)

turtle.mainloop()

我打算在circle()中调用arc()函数,就像在polygon()中调用circle()一样,但是我对应该如何做感到困惑。除此之外,arc()函数不会绘制任何东西,而只是显示给我固定的Turtle。

我认为Turtle对象bob没有收到polygon()中分配的任何移动指令。因此,它所做的就是显示Turtle对象!

我可能是错的,这是我需要澄清的地方。我应该在circle()中调用arc()并移动Turtle对象吗?有更简单的选择吗?在函数中调用函数仍然让我感到困惑,因此,更多的资源来学习它们也将是很棒的!

3 个答案:

答案 0 :(得分:1)

  

我正在尝试...调用circle()函数   就像在circle()内调用了polygon()一样,在arc()内

您已经落后了。问题指出:

  

制作更通用的圆弧,称为arc

就像您可以使用更通用的功能polygon()绘制一个圆一样,您也应该能够使用更通用的功能arc()绘制一个圆。这是一个考虑这个的基本程序:

from turtle import Screen, Turtle
from math import pi

def polygon(turtle, sides, length):
    outside_angle = 360 / sides

    for _ in range(sides):
        turtle.forward(length)
        turtle.left(outside_angle)

def circle_using_polygon(turtle, radius):
    circumference = 2 * pi * radius
    sides = min(60, int(circumference / 3))
    length = circumference / sides
    polygon(turtle, sides, length)

def arc(turtle, radius, angle):
    # implement arc not by calling *circle() nor by
    # calling polygon() but rather by borrowing code
    # from both and adding one more step to reduce
    # the number of sides based on the arc angle

def circle_using_arc(turtle, radius):
    arc(turtle, radius, 360)

bob = Turtle(visible=False)

# Draw overlapping circles three different ways:

bob.color("green")
circle_using_polygon(bob, 100)

for color in ['cyan', 'magenta', 'yellow', 'black']:
    bob.color(color)
    arc(bob, 100, 90)

bob.color("blue")
circle_using_arc(bob, 100)

screen = Screen()

screen.mainloop()

答案 1 :(得分:0)

import turtle
bob=turtle.Turtle()
import math
def arc(t,radius,angle):
    circumference = 2.0*math.pi*radius
    frac = angle/360.0
    arclength = circumference*frac
    n = 50 # pick a number
    len = arclength/n;
    turnang = angle/n
    for i in range(n):
        t.fd(len)
        t.lt(turnang)
arc(bob, 130,360)
turtle.done()

答案 2 :(得分:0)

import tkinter
import swampy
from swampy.TurtleWorld import *

def polygon(n, t, length, angle):
    print(t)
    k= angle/360
    for i in range(0,int(n*k)):
        fd(t, length)
        p= 360
        lt(t,p/n)
        t.delay
world = TurtleWorld()
bob = Turtle()
#def circle(r):
    #l1= 2*3.14*r
    #l= l1/60
    #polygon(30, bob, l)

polygon(60, bob, 10, 180)