如何判断Python Turtle是否在正方形内

时间:2018-10-31 03:10:58

标签: python turtle-graphics

我正在用两只海龟写寻宝代码。两者均设置为随机坐标-用户将使用其中的一个坐标,而另一个坐标将绘制一个正方形,该正方形应作为地图的宝藏区域。我遇到的问题是试图告诉乌龟何时在正方形的边界内。 这是我目前所拥有的:

import turtle
from random import randint
#create turtle and its shape
pepe= turtle.Turtle()
pepe.shape("turtle")
pepe.color("blue")
pepex=randint(0,250)
pepey=randint(0,250)
pepe.setposition(pepex, pepey)
#create a new screen and set screen size
scrn1 = turtle.Screen ()
scrn1.screensize(500,500)
scrn1.bgcolor("pink")
scrn1.title("Treasure hunt")
#create turtle that draws treasure square, set in random positon
pat = turtle.Turtle()
pat.shape("arrow")
pat.color("red")
patx=randint(0,250)
paty=randint(0,250)
pat.setposition(patx, paty)
pat.begin_fill()
for i in range (4):
    pat.forward(30)
    pat.left(90)
pat.end_fill()
#prompt user if they want to go on a treasure hunt
treasure_hunt=input("Do you want to go on a treasure hunt? Press y to continue")
while treasure_hunt=='y':
    #ask user for input to move their turtle, each time sets the angle back to 0 to move right and 90 to move up
    left_or_right=int(input("Enter number between -250 and 250 to move left or right"))
    pepe.seth(0)
    pepe.forward(left_or_right)
    up_or_down=int(input("Enter number between -250 and 250 to move up or down"))
    pepe.seth(90)
    pepe.forward(up_or_down)
    if pepe.distance(pat) ==0:
        break
pat.write("You did it!", font=("Arial", 16, "normal"))

1 个答案:

答案 0 :(得分:0)

解决此问题的一种简单方法是让updateQuery(){ this.set('flag', false); this.transitionToRoute('search-results'); } 成为宝藏,而不是抽出宝藏。无需绘制正方形,而是将光标变为正方形,调整其大小,然后将其放置在所需的位置。然后,两只乌龟之间的pat方法就有意义了:

distance()

enter image description here