我创造了2只乌龟,它们一直在移动,直到其中一只撞到墙上,导致它们完全停止。在
我的问题是,当它撞到墙上/另一只乌龟时,它会转身而不是停下来继续前进?我对如何用1只海龟做这个有一个粗略的想法,但是每当我尝试用2只海龟时,它就是不起作用。在
import random
import turtle
def moveRandom(wn, t):
coin = random.randrange(0,2)
if coin == 0:
t.left(90)
else:
t.right(90)
t.forward(50)
def areColliding(t1, t2):
if t1.distance(t2) < 2:
return True
else:
return False
def isInScreen(w, t):
leftBound = - w.window_width() / 2
rightBound = w.window_width() / 2
topBound = w.window_height() / 2
bottomBound = -w.window_height() / 2
turtleX = t.xcor()
turtleY = t.ycor()
stillIn = True
if turtleX > rightBound or turtleX < leftBound:
stillIn = False
if turtleY > topBound or turtleY < bottomBound:
stillIn = False
return stillIn
t1 = turtle.Turtle()
t2 = turtle.Turtle()
wn = turtle.Screen()
t1.shape('turtle')
t2.shape('circle')
leftBound = -wn.window_width() / 2
rightBound = wn.window_width() / 2
topBound = wn.window_height() / 2
bottomBound = -wn.window_height() / 2
t1.up()
t1.goto(random.randrange(leftBound, rightBound),
random.randrange(bottomBound, topBound))
t1.setheading(random.randrange(0, 360))
t1.down()
t2.up()
t2.goto(random.randrange(leftBound, rightBound),
random.randrange(bottomBound, topBound))
t2.setheading(random.randrange(0, 360))
t2.down()
while isInScreen(wn, t1) and isInScreen(wn, t2):
moveRandom(wn, t1)
moveRandom(wn, t2)
wn.exitonclick()
实际上,您需要重新组织代码,以避免重复。在
让我们创造世界的特性
^{pr2}$以及它的生物
一些物理约束
定义每个普通海龟的大脑
让我们来定义如何使这个世界充满活力,并使之充满活力
这里有一个你的代码的重做,我相信它能满足你的需要。我的大多数其他更改都是对代码的简化。一个主要的改变是我抛出了移动海龟的
while()
循环,并将它们放在自己的计时器上:为了处理这些碰撞,我调用了
isInScreen(t)
和areColliding(t1, t2)
中的moveRandom(wn, t)
并简单地撤消移动,如果它导致了碰撞,则转向相反的方向移动。在相关问题 更多 >
编程相关推荐