第 4.3 节 练习 #5 - Allen Downey 的"Think Python"



可以在此处访问练习链接 - 案例研究:界面设计,练习部分 4.3

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

制作一个更通用的circle版本,称为arc,它接受一个额外的参数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()

我打算在arc()中调用circle()函数,就像在circle()中调用polygon()一样,但我对应该如何做到这一点感到困惑。除此之外,arc()函数没有绘制任何东西,而只是向我展示了一只静止的。

我相信海龟对象bob没有收到polygon()内分配的任何移动指令。因此,它所做的只是显示海龟对象!

我可能是错的,这是我需要澄清的地方。我应该在arc()内调用circle()以及让海龟对象移动吗?有更简单的替代方案吗?在函数中调用函数对我来说仍然令人困惑,因此了解更多有关它们的资源也会很棒!

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()

我正在尝试...调用 circle(( 函数 在 arc(( 中调用,就像在 circle(( 中调用 polygon((

一样

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

制作一个更通用的圆版本,称为 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()
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)

最新更新