【问题标题】:How to make all the turtles move simultaneously如何让所有海龟同时移动
【发布时间】:2020-06-16 03:54:21
【问题描述】:

我想同时移动所有海龟,我希望能够创建 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】:

    您不需要“一个聪明人”来解决这个问题,您需要花费更多自己的时间在 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()
    

    【讨论】:

    • 说“聪明的人”只是很好我知道这并不需要太多,但是很好,是的,我正在努力学习和寻找答案,这是帮助我的一部分学习并在我的学习过程中为我节省大量时间。
    最近更新 更多