首页 > 解决方案 > 蟒龟形状

问题描述

我正在尝试使用 python turtle 在正方形内绘制一个倾斜的正方形。但是我没有得到我想要的形状

这是我迄今为止的代码 -

import turtle as t
t.speed(1)

def square(x, y, side):
    t.setpos(x,y)
    for i in range(4):
        t.forward(side)
        t.right(90)


#square(0,0,100)    

def tiltsquare(x, y, side):
    t.setpos(x,y)
    t.left(45)
    for i in range(4):
        t.forward(side)
        t.right(90)

#tiltsquare(-50,-50,100)  

def squareinsquare(x,y,side):
    square(0,0,200)
    t.forward(100)
    tiltsquare(0/2,0/2, 100)

squareinsquare(0,0,0)

标签: python

解决方案


您需要弄清楚内部/倾斜正方形应该从哪里开始,以及边有多长:

from turtle import Turtle, Screen
import math

t = Turtle()
s = Screen()
t.speed(3)

def square(x, y, side):
    t.setpos(x,y)
    for i in range(4):
        t.forward(side)
        t.right(90)

def tiltsquare(x, y, side):
    t.left(45)
    square(x, y, side)

def squareinsquare(x, y, side):
    square(x, y, side)

    # the middle of the left side is (x, y - side/2)
    # the length of the sides in the tilted square is
    # (using pythagoras)
    half = side / 2
    b = math.sqrt(half**2 + half**2)

    tiltsquare(x, y - side/2, b)

squareinsquare(0, 0, 200)
screen.exitonclick()

输出

在此处输入图像描述

只是为了好玩......如果你想以一个角度绘制正方形,你需要概括内正方形的起点:

def squareinsquare(x, y, side, angle):
    t.right(angle)
    square(x, y, side)

    half = side / 2

    # the starting x,y of the inner/tilted square
    angle = math.radians(angle)
    x -= half * math.sin(angle)
    y -= half * math.cos(angle)
    
    # the length of the sides in the tilted square is
    # (using pythagoras)
    b = math.sqrt(half**2 + half**2)

    tiltsquare(x, y, b)


squareinsquare(0, 0, 200, 25)

给予

在此处输入图像描述

x 和 y 通过求解三角形 abc 得到:

在此处输入图像描述


推荐阅读