How to generate Turtle objects automatically?

Question:

I want to generate (a) amount of the same RawTurtle object, while all being named separately. It seems like something that should be doable, but I don’t know how.

Here’s my code:

def spawnEntity(a):
    for x in range(0, a):
        global entity
        spawnpt = (rand.randrange(-(cWidth/2), cWidth/2), rand.randrange(-(cHeight/2), cHeight/2))
        entName = (f'entity{x}')
        def entGenerate(a):
            print(a)
            (f'{a}') = turtle.RawTurtle(screen)
            (f'{a}').shape("square")
            (f'{a}').speed("fastest")
            (f'{a}').penup()
            (f'{a}').pencolor("gray")
            (f'{a}').fillcolor("gray")
            (f'{a}').setpos(spawnpt)
            print(a)
        entGenerate(entName)
        entList = []
        entList.append(entName)

proportion = (16, 9)
cWidth = (proportion[0] * 80)
cHeight = (proportion[1] * 80)

root = Tk()
root.title("Shooter Game")

canvas = Canvas(master=root, width=cWidth, height=cHeight)
canvas.grid(row=1, column=1)
screen = turtle.TurtleScreen(canvas)
    
spawnEntity(4)
    
root.mainloop()

Update: Problem solved! The new code below runs all 4 turtles (aka: "entities") independently from each other, while still being able to all be called under a for loop:

def spawnEntity(a):
    global ent, entity
    ent = (a)
    entity = {num: turtle.RawTurtle(screen) for num in range(ent)}
    for i in range(ent):
        spawnpt = (rand.randrange(-(cWidth/2.5), cWidth/2.5), rand.randrange(-(cHeight/2.5), cHeight/2.5))
        entity[i].shape("square")
        entity[i].speed("fastest")
        entity[i].penup()
        entity[i].pencolor("gray")
        entity[i].fillcolor("gray")
        entity[i].setpos(spawnpt)
Asked By: Getlo

||

Answers:

You can use a dict:

import turtle

a = 10
turtles = {num: turtle.Turtle for num in range(a)}

Now, whenever you want to call a specific turtle, you can use the dictionary like so:

turtles[1].forward(100)



The above is the way to do it, but just so you know, there is a way to make individual variables for each turtle, but it’s would be DANGEROUS. You can either use locals or exec.

For locals:

import turtle

a = 10
for num in range(a):
    locals()[f"turt{num}"] = turtle.Turtle()
    
turt1.forward(100)

For exec:

import turtle

a = 10
for num in range(a):
    exec(f"turt{num} = turtle.Turtle()")

turt1.forward(100)

If you want to call a specific turtle to do something use its string name, you can use eval:

eval("turt1.forward(100)")

Remember, the above code is DANGEROUS, here is why:

Answered By: Ann Zen