python - 堆叠三角形,同时使用 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()
这是我期望得到的:
这是我从我的代码中得到的:
解决方案
想想三角形边的大小。在 的第一次迭代中for shape in range(...)
,你有一个很1 * 20 = 20
长的边。在第二个中,您有2 * 20 = 40
. 第三,你有60
. 在第四个,你有80
。2
这并不是每次都增加一个因子。按照您的编码方式,您需要将大小增加到其最后一个值的两倍以获得对称图形:
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()
推荐阅读
- php - 在 web.php 第 5 行中找不到类
- php - 如何在 laravel 中将 word 文档文本转换为 HTML?
- html - 为容器设置 CSS 渐变
- java - Java 内置邻接表
- java - 如何检查我的jPanel(#java#netbeans)中是否单击(选择)了某个对象(圆圈)?
- javascript - 有新更新时自动添加到 DOM
- .net - 未显示未处理的异常消息
- javascript - jQuery UI Draggable:水平滚动无法将第一列移动到最后一列
- python - TypeError:“int”对象在 Python3 中不可下标
- laravel - 如何在 laravel 的一列上分组?