如何将 turtle 对象与 python 中的 class 实例连接起来?

How can I connect a turtle object with an instance of a class in python?

我是 python 的新手,我正在尝试使用 turtle 库创建一个简单的竞赛游戏。

我有一辆汽车 class 和一个世界 class。在世界中 class 我想创建一个汽车实例。

这是class车

class Car():
def __init__ (self, brand, acceleration, maxSpeed):
    self.brand = brand
    self.acceleration = acceleration
    self.maxSpeed = maxSpeed
    print(f'{self.brand} has an acceleration of {self.acceleration} and a max speed of {self.maxSpeed}\n')

这里是 class 世界。它还没有完成! 我希望这能解决我的问题,但没有解决 -> car1 = 汽车 ('bmw', 2.5, 200)

car1 = tr.Turtle()

class World:
def __init__(self):
    self.screen = tr.Screen ()
    self.screen.listen ()
    self.screen.onkey (self.forward, 'a')
    self.screen.onkey (self.backward, 'z')
    self.time = tm.time ()

car1 = Car ('bmw', 2.5, 200)
car1 = tr.Turtle()

def forward (self):
    self.carOne.fd(45)        
    print ('aaaaaaaaaaaaaaaaaaa')
    
def backward (self):
    self.carOne.back(45)
    print ('zzzzzzzzzzzzzzzzzz')

def run (self):
    while True:                 # Main real-time simulation loop
        # BEGIN mandatory statements
        self.oldTime = self.time
        self.newTime = tm.time ()  # The only place where the realtime clock is repeatedly queried
        self.deltaTime = self.newTime - self.oldTime
        # END mandatory statements
        
        # ... other code, using objects that are in the world, like a racetrack and cars
        # baan = self.Track(selfO.deltaTime)


        # print (self.deltaTime)
        self.screen.update ()
        tm.sleep (0.02)         # Needed to free up processor for other tasks like I/O

world = World ()
world.run ()

我的问题是如何创建一个连接到 Car 实例的 turtle 对象 class?

例如,在汽车的构造函数中,我给它起了一个名字和一个速度和加速度 -> 这是在一个方法中计算出来的。

所以我想要的是乌龟对象获得与汽车实例相同的参数。你也可以说我想让乌龟对象成为汽车的实例。

想法是以后再增加汽车。

这可能吗?如果没有,还有其他方法吗?

以下行将 car1Car class 对象重新定义为 tr.Turtle() 对象。它不会具有您之前定义的任何特征。

car1 = Car ('bmw', 2.5, 200)
car1 = tr.Turtle()

可能可行的方法是在 Car 构造函数中实例化一个 tr.Turtle()。这可能看起来像

class Car:
    def __init__(self, type, num1, num2):
        self.type = type
        self.num1 = num1
        self.num2 = num2
        self.turtleBoi = tr.Turtle()
car1 = Car('bmw', 2.5, 200)
car1.turtleBoi.forward(15)