python小乌龟行走轨迹_python – 两个随机行走的乌龟的无限循环

在我抓住了我之前的程序(乌龟随机走动并从墙上反弹直到它击中它们4次)之后,我尝试在指南中进行以下练习,要求两只乌龟随机出发位置四处走动屏幕和墙壁反弹,直到它们相互碰撞 – 没有反作用的变量来决定它们什么时候停止.我设法写了整个东西,除了它们碰撞和停止的部分:我想一个布尔函数,如果海龟的X和Y坐标是相同的,则返回True,如果它们不是,则返回False,而是他们继续走路,终止程序的唯一方法是强制解释器退出.我究竟做错了什么?

import turtle

import random

def setStart(t):

tx = random.randrange(-300,300,100)

ty = random.randrange(-300,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 stillIn

def collide(t,u):

if t.xcor() == u.xcor() and t.ycor() == u.ycor():

return True

return False

def 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,u,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-3-x,turtle-graphics

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值