让所有海龟同时移动

问题描述 投票:0回答:1

我想同时移动所有海龟,并且希望能够创建100只海龟。我必须在代码中分别创建一个,因此要创建100个或更多的代码将花费很长时间。我希望有一种方法可以设置所需的海龟数量-从100以上的数量。我希望他们同时行动。我也想设置边界。关于如何执行所有或全部操作的任何想法将不胜感激。

希望这里有一个聪明的人可以提供帮助。

总结,我希望能够:

  • 设置生成的海龟数量。
  • 一次移动所有内容,而不是一个每次。
  • 设置边界,使其不能走到任何地方。

注意:我也知道有几个问题要问,但没有提供有效的答案。我的代码:

import turtle
import numpy as np

tlist = list()
colorlist = ["red", "green", "black", "blue", "brown"]
for i in range(5):
    tlist.append(turtle.Turtle(shape="turtle"))
    tlist[i].color(colorlist[i])
    tlist[i].speed(1)
screen = turtle.getscreen()
for i in range(30):

    for t in tlist:
        t.speed(1)
        t.right((np.random.rand(1) - .5) * 180)
        t.forward(int((np.random.rand(1) - .5) * 100))
    screen.update() 
python python-3.x python-turtle
1个回答
0
投票

您不需要“一个聪明的人在这里”来解决这个问题,您需要花费更多的时间来搜索大量关于SO的海龟示例。但是,我将这作为个人挑战,编写极简代码以将100只海龟置于有限的随机运动中:

from turtle import Screen, Turtle
from random import randint

WIDTH, HEIGHT = 600, 600
CURSOR_SIZE, TURTLE_SIZE = 20, 10
TURTLES = 100

def move():
    for turtle in screen.turtles():
        turtle.forward(1)
        x, y = turtle.position()

        if not (TURTLE_SIZE - WIDTH/2 < x < WIDTH/2 - TURTLE_SIZE and TURTLE_SIZE - HEIGHT/2 < y < HEIGHT/2 - TURTLE_SIZE):
            turtle.undo()  # undo forward()
            turtle.setheading(randint(1, 360))  # change heading for next iteration

    screen.update()
    screen.ontimer(move)

screen = Screen()
screen.tracer(False)
screen.setup(WIDTH, HEIGHT)

for turtle in range(TURTLES):
    turtle = Turtle()
    turtle.penup()
    turtle.shapesize(TURTLE_SIZE / CURSOR_SIZE)
    turtle.shape('turtle')
    turtle.setheading(randint(1, 360))
    turtle.goto(randint(TURTLE_SIZE - WIDTH/2, WIDTH/2 - TURTLE_SIZE), randint(TURTLE_SIZE - HEIGHT/2, HEIGHT/2 - TURTLE_SIZE))

move()

screen.exitonclick()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.