import turtleimport randomdef setStart(t): tx = random.randrange(-300,300,100) ty = random.randrange(-300,100) t.penup() t.goto(tx,ty) t.pendown()def throwCoin(t): coin = random.randrange(0,2) if coin == 0: t.left(90) else: t.right(90)def isInScreen(w,t): leftBound = w.window_wIDth() / -2 rightBound = w.window_wIDth() / 2 bottomBound = w.window_height() / -2 topBound = w.window_height() / 2 turtlex = t.xcor() turtley = t.ycor() stillin = True if turtlex < leftBound or turtlex > rightBound or turtley < bottomBound or turtley > topBound: stillin = False return stillindef collIDe(t,u): if t.xcor() == u.xcor() and t.ycor() == u.ycor(): return True return Falsedef randomWalk(t,w): if not isInScreen(w,t): t.left(180) else: throwCoin(t) t.forward(100)def doubleRandom(t,u,w): while not collIDe(t,u): randomWalk(t,w) if collIDe(t,u): break randomWalk(u,w)wn = turtle.Screen()wn.bgcolor('lightcyan')steklovata = turtle.Turtle()steklovata.color('darkslategray')steklovata.shape('turtle')setStart(steklovata)catshower = turtle.Turtle()catshower.color('orangered')catshower.shape('turtle')setStart(catshower)doubleRandom(steklovata,catshower,wn)wn.exitonclick()
编辑:为了测试错误是在碰撞(t,u)函数还是在调用它的while循环中,我编写了另一个函数,将两只乌龟发送到同一个地方并打印出一些文本(如果有人想知道,如果碰撞(t,u)返回True,那就是内幕笑话,就像我提出的每个翻转名字一样.当我运行它时,文本DID打印出来,这告诉我碰撞检测工作正常…但是循环不知何故告诉Python龟会在碰撞时停止.这是功能:
def raul(t,w): t.goto(1,1) u.goto(1,1) if collIDe(t,u): t.write('RAul SUNTASIG')
这会给你们任何想法,为什么它不起作用?
解决方法 编辑:完全改变了答案.我在碰撞例程中添加了print语句并获得了:
-300.0 -200.0 -100.0 -100.0-300.0 -100.0 -100.0 -100.0-300.0 -100.0 -200.0 -100.0-300.0 -100.0 -200.0 -100.0-300.0 1.13686837722e-13 -200.0 -100.0-300.0 1.13686837722e-13 -200.0 1.27897692437e-13-300.0 1.13686837722e-13 -200.0 1.27897692437e-13-200.0 4.02080297728e-14 -200.0 1.27897692437e-13-200.0 4.02080297728e-14 -200.0 100.0-200.0 4.02080297728e-14 -200.0 100.0
以下是您修复它的方法:
def collIDe(t,u): if abs(t.xcor() - u.xcor()) < 1 and abs(t.ycor() - u.ycor()) < 1: return True return False
哦,你应该在每个randomWalk()之后进行碰撞()检查,而不仅仅是第一个.
总结以上是内存溢出为你收集整理的python – 两个随机行走的乌龟的无限循环全部内容,希望文章能够帮你解决python – 两个随机行走的乌龟的无限循环所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)