How to initialize multiple turtles in Python with classes

 ̄綄美尐妖づ 提交于 2021-01-28 06:59:26

问题


I am a beginner at Python and I'm new to Stack Exchange. I'm trying to write a program that has 5 turtles moving within a square. I've got code that does what I want, but it's tedious and I'd like to initialize all my turtles using classes instead of doing it one by one. I just want them to start out at random coordinates and with a random heading.

The problems with my code:

  • Only one turtle is shown on screen. Two are defined in the code below.

  • The turtle's heading and coordinates aren't being initialized.

Here's the code that I've tried:

import numpy as np
from turtle import *

# setting up screen
reset()
screensize(550)
Screen().bgcolor('black')
tracer(0)

# drawing box
t0 = Turtle()
t0.penup()
t0.goto(-256,-256)
t0.color('cyan')
t0.pendown()
for i in range(4):
    t0.forward(512)
    t0.left(90)
t0.ht()

# parameters
velocity = 5
iterations = 200
boxsize = 512
ranheader = np.random.random()*360
ranx = np.random.random()*boxsize
rany = np.random.random()*boxsize

class turtle_agents(Turtle):
    def _init_(self):
        self.up()
        self.seth(ranheader)
        self.setpos(ranx,rany)
        self.velocity = velocity
        self.down()

# turtle
t1 = turtle_agents()
t1.color('green')
t2 = turtle_agents()
t2.color('blue')

# turtle movement
for turtle in turtles():
    for i in range(iterations):
        turtle.forward(velocity)
        if turtle.xcor() >= 256:
            turtle.goto(-256,t0.ycor())
        elif turtle.xcor() <= -256:
            turtle.goto(256,t0.ycor())
        elif turtle.ycor() >= 256:
            turtle.goto(t0.xcor(),-256)
        elif turtle.ycor() <= -256:
            turtle.goto(t0.xcor(),256)

update()    
exitonclick()

回答1:


You should consider storing your turtles in a list, as the turtles are already objects and you don't need to create a class just to move them to your starting positions. Lists in Python are incredibly powerful because they can store arbitrary data types. Here, I will create 5 turtles and move them so you can tell them apart:

import turtle
num_turtles = 5
my_turtles = [turtle.Turtle() for i in range(num_turtles)]
for i, turt in enumerate(my_turtles):
    turt.forward(50 * i)

You want to do the same thing, just replace my turt.forward() line with whatever you want the turtles to do. In your case, go to a random position within your square.




回答2:


only one turtle shown on screen. Two are defined in the code below. the turtle's heading and coordinates aren't being initialized.

I believe the problem is that you defined the random position and heading once, outside the turtle creation loop so they all start in the same place, move in the same direction at the same speed. I.e. they're right on top of each other.

We don't need @BlivetWidget's explicit List to fix the problem since, as you discovered, turtles are already maintained in a list which we can get via the screen's turtles() method. Below is my rework of your code to fix various issues:

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

# parameters
COLORS = ['green', 'blue', 'red', 'orange', 'white']
ITERATIONS = 500
VELOCITY = 5
BOX_SIZE = 512

# setting up screen
screen = Screen()
screen.setup(BOX_SIZE + 50, BOX_SIZE + 50)
screen.bgcolor('black')
screen.tracer(False)

# drawing box
turtle = Turtle()
turtle.hideturtle()
turtle.color('cyan')

turtle.penup()
turtle.goto(-BOX_SIZE/2, -BOX_SIZE/2)
turtle.pendown()

for _ in range(4):
    turtle.forward(BOX_SIZE)
    turtle.left(90)

# turtle
for color in COLORS:
    angle = randrange(360)
    x = randint(-BOX_SIZE/2, BOX_SIZE/2)
    y = randint(-BOX_SIZE/2, BOX_SIZE/2)

    turtle = Turtle()
    turtle.color(color)
    turtle.setheading(angle)
    turtle.penup()
    turtle.setposition(x, y)
    turtle.pendown()

# turtle movement
for _ in range(ITERATIONS):
    for turtle in screen.turtles():
        turtle.forward(VELOCITY)

        x, y = turtle.position()

        if x >= BOX_SIZE/2:
            turtle.penup()
            turtle.setx(-BOX_SIZE/2)
            turtle.pendown()
        elif x <= -BOX_SIZE/2:
            turtle.penup()
            turtle.setx(BOX_SIZE/2)
            turtle.pendown()
        elif y >= BOX_SIZE/2:
            turtle.penup()
            turtle.sety(-BOX_SIZE/2)
            turtle.pendown()
        elif y <= -BOX_SIZE/2:
            turtle.penup()
            turtle.sety(BOX_SIZE/2)
            turtle.pendown()

    screen.update()

screen.exitonclick()

I agree with @BlivetWidget that "you don't need to create a class just to move them to your starting positions". I use a simple loop above.



来源:https://stackoverflow.com/questions/33767122/how-to-initialize-multiple-turtles-in-python-with-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!