0

我想在知道矩形长度和宽度以及矩形数量的情况下绘制(这个形状)多边形,

在此处输入图像描述

这是我的代码:

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()

但是这段代码没有显示想要的形状,那么我怎样才能画出上面的形状呢?

4

4 回答 4

1

您的矩形具有正确的方向,但位置错误。我的解决方案是让每个循环在图像的中心开始和结束。这确保了矩形都在中心。

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    # go to corner:
    penup()
    forward(length/2)
    right(90)
    forward(width/2)
    right(90)
    pendown()
    # draw rectangle:
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    # go back to centre:
    penup()
    forward(length/2)
    right(90)
    forward(width/2)
    left(90)
    pendown()
    # turn
    right(180/num_of_rectangles)

done()
于 2020-06-02T19:19:08.940 回答
1

您可以将矩形绘制为 5,而不是将矩形绘制为 4 笔画,从其中一个边的中间开始和结束。您还需要在笔向上的情况下到达那一侧的中间,然后回到中心(再次将笔向上):

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
penup()
for i in range(num_of_rectangles):
    # Get to middle of side and orient for drawing
    forward(width / 2)
    right(90)
    pendown()
    # Draw rectangle in 5 strokes
    forward(length / 2)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length / 2)
    penup()
    # Reorient and get back to center
    left(90)
    backward(width / 2)
    right(180/num_of_rectangles)

done()
于 2020-06-02T19:29:01.013 回答
1

您使用了错误数量的矩形(您只需要 6 个,而不是 8 个)以及矩形的错误纵横比。(它比 50x20 更接近 50x32。)其他一些建议的解决方案继承了这些相同的错误,使用太多代码来解决问题,并且看起来不像提供的图像:

from turtle import Screen, Turtle

WIDTH, HEIGHT = 200, 130
RADIUS = 120
PEN_WIDTH = 8

turtle = Turtle()
turtle.hideturtle()
turtle.width(PEN_WIDTH)

for _ in range(6):
    turtle.penup()
    turtle.circle(RADIUS, extent=30)
    turtle.pendown()

    turtle.left(57)

    for _ in range(2):
        turtle.forward(WIDTH)
        turtle.left(90)
        turtle.forward(HEIGHT)
        turtle.left(90)

    turtle.right(57)

screen = Screen()
screen.exitonclick()

在此处输入图像描述

要更改图像的大小,请将 、 和 乘以或除以相同WIDTH的因子。HEIGHTRADIUSPEN_WIDTH

于 2020-06-02T22:05:57.323 回答
0

这里有一些东西:

from turtle import *
ht() # Hides turtle
w,h,n = 130,200,6 # Set the width,height & amount of rectangles
for _ in range(n):
    pu()
    fd(h//2) # Note the double slashes to avoid error
    pd()
    for f in [w//2,h,w,h,w//2]:
        rt(90)
        fd(f)
    pu()
    rt(90)
    fd(h//2)
    rt(180-180//n)

图片

于 2020-06-04T02:52:01.987 回答