如何自动生成 Turtle 对象?

How to generate Turtle objects automatically?

我想生成 (a) 数量的相同 RawTurtle 对象,同时全部单独命名。好像应该可以实现,但是不知道怎么实现。

这是我的代码:

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()

更新:问题已解决!下面的新代码运行所有 4 只海龟(又名:“实体”)彼此独立,同时仍然能够在 for 循环下全部调用:

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)

您可以使用 dict:

import turtle

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

现在,无论何时你想调用特定的海龟,你都可以像这样使用字典:

turtles[1].forward(100)



以上是实现方法,但你要知道,一种为每只海龟制作单独变量的方法,但它是危险。您可以使用 localsexec.

对于locals

import turtle

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

对于exec

import turtle

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

turt1.forward(100)

如果你想调用一个特定的乌龟来做一些使用它的字符串名称的事情,你可以使用eval:

eval("turt1.forward(100)")

记住,上面的代码是危险的,原因如下: