试图让两只在一个正方形中随机移动,并说它们何时靠近



所以我的任务是:

  1. 制作一个蓝色矩形
  2. 编写一个函数,使湍流在90度的间隔内沿随机方向移动,并在0-25的随机间隔内向前移动
  3. 创建一个蓝色正方形
  4. 将草皮移动到正方形中的一个随机点
  5. 编码,这样乌龟离开时就会移回广场
  6. 创建一个附加的草皮(两者都应该有不同的颜色(
  7. 使用相同的语句将两只乌龟(使用move_random函数(移动500次
  8. 如果海龟接近50个单位-打印一个字符串,计算它们接近50个单元的次数

它应该是这样的:在此处输入图像描述

我添加了一些评论来解释我的思维过程

感谢提供的任何帮助

代码:

编辑:修复了缩进,现在我在最后一行得到了错误消息,即名称";满足";未定义。此外,如果我在没有最后一行的情况下运行代码,该行应该打印近距离接触的数量,则不会发生任何事情,不会出现错误,但也不会出现海龟。

import turtle
import random
#makes the jump function
def jump(t, x, y):
t.penup()
t.goto(x, y)
t.pendown()  
#creares a turtle at a defined place    
def make_turtle(x, y):
t = turtle.Turtle()
jump(t, x, y)    # Use of the function defined above
return t
#function to create a rectangle and fill it with a color
def rectangle(x, y, width, height, color):
t = make_turtle(x, y)
t.speed(0)
t.hideturtle()
t.fillcolor(color)
t.begin_fill()
for dist in [width, height, width, height]:
t.forward(dist)
t.left(90)
t.end_fill()

#function to move turtle in a random heading (90 degree interval) between 0--25 units forward
#While also making it turn around if it is outside of the square
def move_random(t):
if abs(t.pos()[0]) >= 250 or abs(t.pos()[1]) >= 250:
target = (0, 0)
d =  (0,0)
t.setheading(d)
else:
ini = t.heading()
new = rd.randint(ini - 45, ini + 45)
t.setheading(new)
t.forward(rd.randint(0, 25))

#creates the square and both turtles   
t = make_turtle(0 , 0)
t.color("green")
t2 = make_turtle(0 , 0) 
t2.color("black")
rectangle(-250, -250, 500, 500, "lightblue")
jump(t, rd.randint(-250, 250), rd.randint(-250, 250))
jump(t2, rd.randint(-250, 250), rd.randint(-250, 250)) #jumps the turles randomly in the square
meet = 0
for i in range(1, 501): #makes the turtles move randomly as specified above
move_random(t)
move_random(t2)
if t.distance(t2) < 50: 
t.write("close")
meet += 1
print(str(meet), "close encounter") #prints the amount of times they are close to each other
if abs(t.pos()[0]) >= 250 or abs(t.pos()[1]) >= 250:
target = (0, 0)
d =  (0,0)
t.setheading(d)
else:

请参阅";否则:"?你错过了一张账单。

最新更新