【问题标题】:Is there a way to make all of the turtles orbit all together?有没有办法让所有的海龟一起绕轨道运行?
【发布时间】:2021-03-02 06:35:09
【问题描述】:

我无法让所有海龟一起画一个圆圈,因为我正在使用 for 循环让这些海龟一个接一个地绕轨道运行,

from turtle import Turtle, Screen
import random

w = Screen()
w.bgcolor('#222')

def color_generator():
    symbols = [str(n) for n in range(5, 10)] + ['a', 'b', 'c', 'd', 'e', 'f']
    pick = [random.choice(symbols) for _ in range(3)]
    color = ''.join(pick)
    return f'#{color}'



class Particle(Turtle):
    def __init__(self):
        super().__init__()
        self.shape('turtle')
        self.penup()
        self.create_particle()

    def create_particle(self):
        self.color(color_generator())
        self.goto(random.randint(-350, 350), random.randint(-350, 350))
        self.seth(random.randint(0, 360))

    def orbit(self):
        self.speed('fast')
        self.pendown()
        for _ in range(25):
            self.forward(10)
            self.right(15)


for _ in range(5):
    t = Particle()
    t.orbit()


w.exitonclick()

我怎样才能让它们全部一起运行?

这是它的作用:

【问题讨论】:

标签: python loops turtle-graphics particles python-turtle


【解决方案1】:

我们可以通过仅通过交错粒子的运动来模拟线程来简化这一点:

from turtle import Turtle, Screen
from random import randint, randrange, choice

def color_generator():
    symbols = [str(n) for n in range(5, 10)] + ['a', 'b', 'c', 'd', 'e', 'f']
    pick = [choice(symbols) for _ in range(3)]
    color = ''.join(pick)
    return f"#{color}"

class Particle(Turtle):
    def __init__(self):
        super().__init__()
        self.shape('turtle')
        self.speed('fastest')
        self.create_particle()

    def create_particle(self):
        self.color(color_generator())
        self.penup()
        self.goto(randint(-350, 350), randint(-350, 350))
        self.setheading(randrange(360))

    def arc(self):
        self.pendown()
        self.forward(10)
        self.right(15)

screen = Screen()
screen.bgcolor('#222')

particles = [Particle() for _ in range(5)]

for _ in range(24):
    for particle in particles:
        particle.arc()

screen.exitonclick()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-17
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2020-01-10
    • 2022-07-23
    相关资源
    最近更新 更多