gpt4 book ai didi

python - 两只 turtle 随机运动

转载 作者:行者123 更新时间:2023-11-30 23:12:34 25 4
gpt4 key购买 nike

我刚刚开始从 Interactivepython.org 学习 Python,并坚持以下练习:

Modify the turtle walk program so that you have two turtles each with a random starting location. Keep the turtles moving until one of them leaves the screen.

这就是我想出来的。程序在 1 次迭代后停止,并且由于某种原因,两只 turtle 从相同的坐标开始。

import turtle
import random

wn = turtle.Screen()

kj = turtle.Turtle()
saklep = turtle.Turtle()
saklep.color('green')


c = random.randrange(1,100)
v = random.randrange(1,100)
b = random.randrange(1,100)
n = random.randrange(1,100)

kj.setx(c)
kj.sety(v)
saklep.setx(b)
saklep.sety(n)

def isinscreen(t,s,w):

leftmost=-(w.window_width())/2
rightmost =(w.window_width())/2
uppermost = (w.window_height())/2
bottommost =-(w.window_height())/2


tx = t.xcor()
ty = t.ycor()
sx = s.xcor()
sy = s.ycor()

if tx > rightmost or ty >uppermost:
return False
elif tx < leftmost or ty < bottommost:
return False
elif sx > rightmost or sy > uppermost:
return False
elif sx < leftmost or sy < bottommost:
return False
else:
return True


while isinscreen(kj,saklep,wn) == True:
for i in random.randrange(1,361):
kj.forward(100)
kj.left(i)
for deg in random.randrange(1,361):
saklep.forward(100)
saklep.right(deg)

wn.exitonclick()
<小时/>

最佳答案

我认为您将 randrangerange 混合在一起。这一行:

for i in random.randrange(1,361):

触发此错误:

TypeError: 'int' object is not iterable on line 47

因为random.randrange(x,y)返回xy内的int。例如13。那么您想要做的事情与 for i in 13 相同,这是行不通的 because for needs an iterable 13 不是。你应该这样做:

my_random_number = random.randrange(1,361)
for i in range(1, my_random_number)

检查此答案 more informations about range .

<小时/>

此行的相同评论:

for deg in random.randrange(1,361):
<小时/>

关于两只 turtle 在同一位置开始问题,实际上这不是真的:根据设计,turtle.Turtle()似乎在位置 (0, 0) 立即绘制它。然后,当您为 kjsaklep 分配一些坐标时,它似乎会用动画移动它们。

仅尝试这部分代码,您就会看到我刚刚描述的情况正在发生:

import turtle
import random

wn = turtle.Screen()

kj = turtle.Turtle()
saklep = turtle.Turtle()
saklep.color('green')

c = random.randrange(1,100)
v = random.randrange(1,100)
b = random.randrange(1,100)
n = random.randrange(1,100)

kj.setx(c)
kj.sety(v)
saklep.setx(b)
saklep.sety(n)

关于python - 两只 turtle 随机运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754504/

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