是否有办法获得并保存海龟的角度以供以后使用?



我正在制作一个程序,用户可以在屏幕上点击3次,它会形成一个三角形。然后它会找到这三条线的中点。接下来,我想让它画3条线垂直于构成三角形的每条线(通过中点)。

我在画垂线时卡住了。我想尝试保存(就像保存位置或坐标一样)海龟bob(连接三角形线条的海龟)在每条线上的角度,然后将中间的海龟(l1,l2,l3)倾斜在该角度上。然后它会让它左右移动,并画出一条线。如果我说得不清楚,我很抱歉,但我真的想不出其他方式来解释。这是我的代码:

import turtle
tur = turtle.Turtle() #draws the dots
bob = turtle.Turtle() #connects the dots
l1 = turtle.Turtle() #middle point of line 1
l2 = turtle.Turtle() #middle point of line 2
l3 = turtle.Turtle() #middle point of line 3
mid = turtle.Turtle() #point where the lines cross, haven't used this one yet
screen = turtle.Screen()
screen.tracer(0,0)
screen.setup(800,800)
tur.ht()
tur.up()
tur.speed(0)
bob.ht()
bob.up()
bob.speed(0)
screen.update()
l1.up()
l2.up()
l3.up()
mid.up()
mid.ht()
dots = 1
def lines():
line()
l1.goto(line_1_mid_cords) #go to middle of lines
l1.dot()
l2.goto(line_2_mid_cords)
l2.dot()
l3.goto(line_3_mid_cords)
l3.dot()
def line():
global line_1_mid_cords, line_2_mid_cords, line_3_mid_cords
line_1_mid_cords = (( bob_x1 + bob_x2 ) /2, ( bob_y1 + bob_y2 ) /2) #get middle coordinates

line_2_mid_cords = (( bob_x2 + bob_x3 ) /2, ( bob_y2 + bob_y3 ) /2)

line_3_mid_cords = (( bob_x1 + bob_x3 ) /2, ( bob_y1 + bob_y3 ) /2)

def dotOnClick(x,y):
global dots, bob_x1, bob_y1, bob_x2, bob_y2, bob_x3, bob_y3

if dots == 1:
if x >= -800 and x <= 800 and y >= -800 and y <= 800: #click on screen
tur.goto(x,y) #go to that point
bob.goto(tur.pos())#bob goes there too
bob_x1 = bob.xcor() #saves bobs coordinates
bob_y1 = bob.ycor()
tur.dot()
bob.down()
screen.update()
dots = 2 

elif dots == 2:
if x >= -800 and x <= 800 and y >= -800 and y <= 800: #when second dot is clicked
tur.goto(x,y) #both tur and bob to to that point and they get connected
bob.goto(tur.pos())
bob_x2 = bob.xcor()
bob_y2 = bob.ycor()
tur.dot() #draws second dot
bob.down()
screen.update()
dots = 3

elif dots == 3:
if x >= -800 and x <= 800 and y >= -800 and y <= 800: #same for 3rd point on screen
tur.goto(x,y)
bob.goto(tur.pos())
bob_x3 = bob.xcor()
bob_y3 = bob.ycor()
tur.dot()
bob.down()
bob.goto(bob_x1,bob_y1) #bob goes to first dot and completes the triangle
lines() #makes the turtles l1, l2, l3 go to the middle points of the triangle lines
screen.update()
dots = 4

elif dots == 4:
if x >= -800 and x <= 800 and y >= -800 and y <= 800: #resets when you click again
tur.clear()
bob.clear()
screen.update()
tur.reset()
bob.reset()
tur.ht()
tur.up()
tur.speed(0)
bob.ht()
bob.up()
bob.speed(0)
screen.update()
dots = 1

turtle.onscreenclick(dotOnClick,1,True)

如果我需要更多地解释我的确切意思,请说出来!

把你的中点乌龟放在它们的位置后,你可以把它们对准三角形的下一个点。

def lines():
line()
l1.goto(line_1_mid_cords) #go to middle of lines
l1.setheading(l1.towards(bob_x2, bob_y2))
l1.dot()
l2.goto(line_2_mid_cords)
l2.setheading(l2.towards(bob_x3, bob_y3))
l2.dot()
l3.goto(line_3_mid_cords)
l3.setheading(l3.towards(bob_x1, bob_y1))
l3.dot()

最新更新