首页 > 解决方案 > 堆叠三角形,同时使用 python 将大小增加一倍

问题描述

我正在尝试创建总共 4 个三角形,它们在中心堆叠在另一个之上,同时尺寸加倍。我似乎大部分都做对了,但由于某种原因,最后两个三角形开始略微向左转向,我哪里错了?以下是我到目前为止编写的代码。

from turtle import *

number_of_shapes = 4

for shape in range(1, number_of_shapes + 1):
    for sides in range(1, 4):
        forward(shape * 20)
        left(120)

    penup()
    left(120)
    forward(shape * 20)
    right(120)
    pendown()

这是我期望得到的:

预期图像

这是我从我的代码中得到的:

结果图片

标签: pythonpython-turtle

解决方案


想想三角形边的大小。在 的第一次迭代中for shape in range(...),你有一个很1 * 20 = 20长的边。在第二个中,您有2 * 20 = 40. 第三,你有60. 在第四个,你有802这并不是每次都增加一个因子。按照您的编码方式,您需要将大小增加到其最后一个值的两倍以获得对称图形:

from turtle import *

number_of_shapes = 4
side = 20

for shape in range(number_of_shapes):
    for sides in range(3):
        forward(side)
        left(120)
    penup()
    left(120)
    forward(side)
    right(120)
    pendown()
    side = side * 2 # Next side is 2x previous value

在此处输入图像描述

如果您不想拥有 的因子2,则需要确保在正确的位置开始新三角形。

for shape in range(1, number_of_shapes + 1):
    for sides in range(1, 4):
        forward(shape * 20)
        left(120)

    penup()
    left(120)
    forward(shape * 20)
    right(120)

    # At this point, the turtle is at a distance of `shape*20` to the left of the top vertex
    # You want it to be at a distance of (shape+1) * 20 / 2 so that your figure is symmetric
    # So move it forward by that amount before you `pendown()`
    dist = shape*20 - (shape+1) * 10
    forward(dist)

    pendown()

在此处输入图像描述


推荐阅读