python - 关于 Turtle 中的循环
问题描述
我想问一个关于我试图在我的程序中使用的某种循环的问题。因此,为此,我将分享我的程序中存在的用于绘制三角形的函数代码;
def drawing_triangle():
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.left(120)
turtle.penup()
turtle.forward(50)
turtle.forward(10)
turtle.pendown()
所以这是绘制三角形的功能,当我尝试运行程序时,它会给出如下输出;
正如您在图片中看到的,它并排打印三角形,但我希望它们在每四个三角形开始一个新行,如下图所示;
总之,我的问题是如何获得第二张图片中的输出?
提前致谢。
解决方案
Have you tried reading over the docs for the turtle
package yet? https://docs.python.org/3.7/library/turtle.html
I think the difficulty you're having comes from all the turtle's motion being relative to its current position. But for making a new "triangle line", you want to "reset" the turtle's position all the way back to the left.
Take a look at the command turtle.setposition(x, y)
-- this sets the turtle's location in an absolute manner. Instead of moving relative to where it currently is, it just "jumps" to (x, y)
.
You could place that command in part of a for-loop after you've drawn a series of triangles to reset to the left. You'll have to manage your for-loop to iteratively set the height so each subsequent row is placed below the last, but that's the only real difficulty.
Alternatively, you could count how many triangles you've drawn so far in a given "triangle line", then relatively re-position backwards by moving left based on width/spacing and how many triangles have been drawn so far. But I think absolute positioning is probably the easier approach and a good technique to get used to anyway.
推荐阅读
- opengl - Nvidia 上的统一寄存器要求与顶点着色器中的采样器
- mysql - 将 MySQL db 与 VB.NET 连接的 ConnectionString 是什么
- node.js - mock require of oracledb using proxyquire to unit test node.js app
- android - 如何在 Kotlin 中删除 ClipboardManager 的 OnPrimaryClipChangedListener?
- python - 如何使用 Python 将 CSV 转换为 JSON?
- java - 什么样的语句不能在服务器端准备?
- symfony4 - Symfony3.2 到 symfony4 security.encoder_factory 已弃用错误
- ios - 给定一个 IOS Bundle ID 如何显示相应的 App Icon
- node.js - Nodejs:数组数据未添加到 mongodb
- rust - 如何在 Rust 中将 u16 的低/高 8 位转换为 u8?