python - 蟒龟形状
问题描述
我正在尝试使用 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)
解决方案
您需要弄清楚内部/倾斜正方形应该从哪里开始,以及边有多长:
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 得到:
推荐阅读
- ios - CoreData 所需类型 = NSManagedObject; 给定类型 = __NSSingleObjectSetI
- java - 我应该使用什么 Java DateTime 类?
- python - 在 Windows 上安装 Conda
- python - 在树莓派 3 B+ 上 DIY Alexa 时“找不到满足评论json 要求的版本”
- regex - 需要拒绝从指定分支合并的管道
- python - 为什么 Idle Python 线程消耗高达 90% 的 CPU?
- wso2 - 无法在 wso2IS-5.6.0 和 wso2AM-2.5.0 之间连接注册表
- geolocation - 如果我想在主题上开发,如何绕过 Shopify 中的重定向?
- webots - 启用 3D 的 Webots R2019 OSM 导入器
- node.js - JanusGraph Gremlin Server 在哪里配置 GraphSONVersion.V1_0?