在 Python Turtle 图形中制作正方形和旋转正方形的更简单方法 [英] Simpler way to make a square and rotated square in Python Turtle graphics

查看:163
本文介绍了在 Python Turtle 图形中制作正方形和旋转正方形的更简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用海龟图形来重新创建此模式:

I'm working in turtle graphics to recreate this pattern:

这可能是一个非常基本的问题,但是有没有更简单的方法可以在正方形内创建旋转的正方形?事实上,我只是用一只乌龟做一个普通的正方形,然后慢慢地移动第二只乌龟到位来绘制旋转的部分.例如:

This is probably a very basic question, but is there a simpler way for me to create that rotated square within a square shape? As it is, I just use one turtle to make a normal square, then slowly move a second turtle into position to draw the rotated part. Ex:

import turtle
alex = turtle.Turtle()
tess = turtle.Turtle()

for i in range(4):
    alex.fd(50)
    alex.lt(90)
tess.pu()
tess.fd(25)
tess.rt(90)
tess.fd(10)
tess.rt(225)
tess.pd()
for i in range(4):
    tess.fd(50)
    tess.lt(90)

这对我来说充其量是笨重的,如果我改变边长(我打算这样做)就行不通了.

Which to me is clunky at best, and doesn't work if I change the side-lengths (which I intend to do).

非常感谢!

推荐答案

我将建议一种与您和其他过于专注于绘制方块的答案相反的方法许多工作要完成.由于这是一个重复的模式,我认为冲压是要走的路,就像现实生活中的重复模式一样.具体:

I'm going to suggest a contrary approach to yours and the other answers which are too focused on drawing squares which will take too much work to complete. Since this is a repeating pattern, I think stamping is the way to go, just like repeated patterns in real life. Specifically:

from turtle import Turtle, Screen

BASE_UNIT = 20

def tessellate(turtle, start, stop, step):
    for x in range(start, stop + 1, step):
        for y in range(start, stop + 1, step):
            turtle.goto(x * BASE_UNIT, y * BASE_UNIT)
            turtle.stamp()
            turtle.left(45)
            turtle.stamp()

alex = Turtle(shape="square")
alex.shapesize(8)
alex.color("red")
alex.penup()

tessellate(alex, -12, 12, 12)

tess = Turtle(shape="square")
tess.shapesize(4)
tess.color("gold")
tess.penup()

tessellate(tess, -6, 6, 12)

screen = Screen()

screen.exitonclick()

输出

海龟图章自然旋转和缩放,而海龟图则不会!

Turtle stamps naturally rotate and scale which turtle drawings do not!

您会注意到的一件事是我的模式并不完全相同.在原版中,组成星星的两个红色(或黄色)方块大小不一样!它们在使模式起作用方面略有不同 - 我将其作为练习留给 OP 纠正此问题.

One thing you'll notice is that my pattern isn't quite the same. In the original the two red (or yellow) squares that make up a star are not the same size! They are slightly different to make the pattern work -- I leave it as an exercise for the OP to correct this.

这篇关于在 Python Turtle 图形中制作正方形和旋转正方形的更简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆