gpt4 book ai didi

python - 当 turtle 到达某个点时停止 turtle ,Python

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:39 29 4
gpt4 key购买 nike

我目前正在上初级编程课,正在完成作业。现在,我必须用模块 turtle build 3 个房子(我完成了):

def drawBody(mover):
#Rectangle part
mover.fillcolor("blue")
mover.begin_fill()
for i in range(2):
mover.forward(100)
mover.right(90)
mover.forward(75)
mover.right(90)
mover.end_fill()


#Triangle part
mover.fillcolor("red")
mover.begin_fill()
mover.left(45)
for i in range(2):
mover.forward(70.5)
mover.right(90)
mover.right(45)
mover.forward(100)
mover.end_fill()







#Create preproduction turtle
import turtle
wn = turtle.Screen()
josh = turtle.Turtle()


pointGoTo = -175
for houses in range(3):
josh.penup()
josh.goto(pointGoTo,0)
josh.pendown()

drawBody(josh)


josh.right(180)
pointGoTo = pointGoTo + 125

wn.exitonclick()

这是 while 代码。所以我想让 turtle 停在某个点,红色方 block 的左上角。我已经尝试了多个点,但只是没有中断/停止。我的语法关闭了吗?还是我处理整条房子的事情都错了?如果我含糊不清,请问你有什么不明白的,我真的很想弄清楚,但我完全没有想法。:

def drawBody(mover):
#Rectangle part
mover.fillcolor("blue")
mover.begin_fill()
for i in range(2):
mover.forward(100)
mover.right(90)
mover.forward(75)
mover.right(90)
mover.end_fill()


#Triangle part
mover.fillcolor("red")
mover.begin_fill()
mover.left(45)
for i in range(2):
mover.forward(70.5)
mover.right(90)
mover.right(45)
mover.forward(100)
mover.end_fill()

mover.left(90)
mover.forward(75)
mover.left(90)
n = mover.position()
print(n)
while True:
mover.forward(100)
n = mover.position()
print(n)
mover.left(90)
mover.forward(5)
mover.left(90)
n = mover.position()
print(n)
mover.forward(100)
mover.right(90)
mover.forward(5)
mover.right(90)


if n == (-75.30,0.00):
break







#Create preproduction turtle
import turtle
wn = turtle.Screen()
josh = turtle.Turtle()


pointGoTo = -175
for houses in range(3):
josh.penup()
josh.goto(pointGoTo,0)
josh.pendown()

drawBody(josh)


josh.right(180)
pointGoTo = pointGoTo + 125

wn.exitonclick()

最佳答案

首先,你检查错了地方,你必须在这里检查:

while True:
mover.forward(100)

mover.left(90)
mover.forward(5)
mover.left(90)
n = mover.position()

if abs(n - (-75.30, 0.00)) < 0.01:
break

mover.forward(100)
mover.right(90)
mover.forward(5)
mover.right(90)

您的检查不成功,因为 n 实际上是 turtle.Vec2D ,并且坐标是 float ,你可以通过print n[0], n[1]看到。 SO 上有很多关于比较 float 的链接,比如 Testing floating point equality , 例如。在您的情况下,您可以:

if abs(n - (-75.30, 0.00)) < 0.01:
break

但我认为,对您来说最好的方法是只绘制固定次数:

mover.left(90)
mover.forward(70)
mover.left(90)
for i in xrange(7):
mover.forward(100)
mover.left(90)
mover.forward(5)
mover.left(90)

mover.forward(100)
mover.right(90)
mover.forward(5)
mover.right(90)

您还必须像这样更改您的代码:

for houses in range(3):
josh.penup()
josh.goto(pointGoTo,0)
josh.pendown()

drawBody(josh)

pointGoTo = pointGoTo + 125

关于python - 当 turtle 到达某个点时停止 turtle ,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942610/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com