首页 > 解决方案 > 如何使用turtle.gotto打印对称六边形

问题描述

我的任务是在一条线上打印对称六边形。

例子 :在此处输入图像描述

我必须创建一个这样的函数:def hexagone(point, longueur,c): 其中点是 X 轴和 Y 轴。“longueur”是六边形的中心和他的任何一个角之间的距离。我确实使用这个距离来计算和获取我的 turtle.gotto() 的每个 x / y 坐标。“C”代表六边形每个部分的颜色。

到目前为止,我可以在点 0,0 完美地绘制六边形:

import turtle
from math import pi, sin, cos



def hexagone(point, longueur,c):
   l= point[0] + longueur

   turtle.up()
   turtle.goto(point)
   turtle.color(c[0]) #black
   turtle.down()
   turtle.begin_fill() 
   turtle.goto(l * cos(4 / 3 * pi), l * sin(4 / 3 * pi))
   turtle.goto(l * cos(5 / 3 * pi), l * sin(5 / 3 * pi))
   turtle.goto(l * cos(0), l * sin(0)) 
   turtle.goto(point) 
   turtle.end_fill()



   turtle.color(c[1])  #blue
   turtle.begin_fill()
   turtle.goto(l * cos(0), l * sin(0)) 
   turtle.goto(l * cos(pi / 3), l * sin(pi / 3))
   turtle.goto(l * cos(pi * 2 / 3), l * sin(pi * 2 / 3))
   turtle.goto(point)  
   turtle.end_fill()



   turtle.color(c[2]) #red
   turtle.begin_fill()
   turtle.goto(l * cos(pi * 2 / 3), l * sin(pi * 2 / 3))
   turtle.goto(-l, point[1])
   turtle.goto(l * cos(4 / 3 * pi), l * sin(4 / 3 * pi))
   turtle.goto(point)
   turtle.end_fill()
   turtle.up()




   return True

hexagone((0,0), 50, ("black",("blue"),("red")))
turtle.done()

第一个六边形是完美的。我在 origin(0,0) 打印它。但是,如果我尝试简单地将 point[0]->(x) 增加,假设 100 : i += 100hexagone((i,0), 50, ("black",("blue"),("red"))) 它在六边形上打印六边形并且变得越来越大。我的公式明显有问题,并且缩放不正确。有谁知道我怎样才能完成这项工作以存档示例中的结果?

标签: pythonturtle-graphics

解决方案


如果你想显示,(100,50)那么你必须使用(0,0)所有计算,并且在计算之后你必须添加100到你使用的x50一个- 所以你创建它然后你移动它ygoto()(0,0)(100,50)

在代码中我使用0而不是point[0]并且point[1]因为我计算(0,0)

后来我得到x,ypoint(这将是100and 50)and 用于每个goto()

goto(... +x, ... +y)

完整代码

import turtle
from math import pi, sin, cos

def hexagone(point, longueur, c):
   l = 0 + longueur # 0 instead of point[0]

   x, y = point

   turtle.up()
   turtle.goto(point)
   turtle.color(c[0]) #black
   turtle.down()
   turtle.begin_fill() 
   turtle.goto(l * cos(4 / 3 * pi )+x, l * sin(4 / 3 * pi)+y)
   turtle.goto(l * cos(5 / 3 * pi)+x, l * sin(5 / 3 * pi)+y)
   turtle.goto(l * cos(0)+x, l * sin(0)+y) 
   turtle.goto(point) 
   turtle.end_fill()

   turtle.color(c[1])  #blue
   turtle.begin_fill()
   turtle.goto(l * cos(0)+x, l * sin(0)+y) 
   turtle.goto(l * cos(pi / 3)+x, l * sin(pi / 3)+y)
   turtle.goto(l * cos(pi * 2 / 3)+x, l * sin(pi * 2 / 3)+y)
   turtle.goto(point)  
   turtle.end_fill()

   turtle.color(c[2]) #red
   turtle.begin_fill()
   turtle.goto(l * cos(pi * 2 / 3)+x, l * sin(pi * 2 / 3)+y)
   turtle.goto(-l+x, 0+y)  # 0 instead of point[1]
   turtle.goto(l * cos(4 / 3 * pi)+x, l * sin(4 / 3 * pi)+y)
   turtle.goto(point)
   turtle.end_fill()
   turtle.up()

   return True

hexagone((0,0), 50, ("black",("blue"),("red")))
hexagone((100,0), 50, ("black",("blue"),("red")))
hexagone((0,100), 50, ("black",("blue"),("red")))
hexagone((100,100), 50, ("black",("blue"),("red")))
turtle.done()

在此处输入图像描述


推荐阅读