我正在尝试使用我相当熟悉的海龟和 OOP 来制作一个自然选择模拟器,这对我来说就像全新的一样好。我似乎无法找到我的具体问题的答案,这可能是因为我只是不明白它。 我的代码目前如下所示:
import turtle
import time
import random
turtle.speed(50)
turtle.setworldcoordinates(-50, -50, 1920, 1080)
class Creature: # This class contains the blueprint for the 'blob' creature.
def __init__(self, speed, location_x, location_y): # Initializes parameters.
self.speed = speed # Speed of the blob.
self.location_x = location_x # X coordinate of the blob, paired with y forms location.
self.location_y = location_y # Y coordinate of the blob, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def spawn(self):
turtle.penup()
turtle.goto(Creature.location_x, Creature.location_y) # Lets the turtle spawn in a random point.
turtle.color("Blue")
turtle.dot(20)
def move(self):
pass
class Apple: # This class contains the blueprint for the food (apples) that the blobs can eat.
def __init__(self, location_x, location_y):
self.location_x = location_x
self.location_y = location_y
def spawn(self):
turtle.penup()
turtle.goto(Apple.location_x, Apple.location_y)
turtle.color("Red")
turtle.dot(20)
blob1 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob2 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob3 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob4 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob5 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob6 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob7 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob8 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob9 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
blob10 = Creature(1.5, random.randint(0, 1000), random.randint(0, 1000))
apple1 = Apple(random.randint(0, 1000), random.randint(0, 1000))
apple2 = Apple(random.randint(0, 1000), random.randint(0, 1000))
apple3 = Apple(random.randint(0, 1000), random.randint(0, 1000))
apple4 = Apple(random.randint(0, 1000), random.randint(0, 1000))
apple5 = Apple(random.randint(0, 1000), random.randint(0, 1000))
Creature.spawn(all)
Apple.spawn(all)
turtle.exitonclick()
我尝试过改变一些事情,但没有任何帮助。一个解释也会非常有帮助,以及一些关于如何防止自己将来遇到这个问题的建议。另外,我不知道是否可能,但是你能让你的程序创建一个类的实例吗?
你有一些错误,但离工作代码已经不远了。
首先,在
spawn()
函数中,您需要将Creature.location_x
和Apple.location_x
更改为self.location_x
。对.location_y
执行同样的操作。
您的下一期将称为
Creature.spawn()
和 Apple.spawn()
。这是调用类本身,但我们要调用类的实例的方法。
blobs = [Creature(1.5, random.randint(0, 1000), random.randint(0, 1000)) for x in range(10)]
apples = [Apple(random.randint(0, 1000), random.randint(0, 1000)) for x in range(5)]
我继续将您的
Creature
和 Apple
放入自己的列表中,因为这更容易处理。这本质上与十五行代码执行相同的操作,但只用了两行。
最后,我们循环遍历每个列表并调用每个
实例的
.spawn()
方法。
for blob in blobs:
blob.spawn()
for apple in apples:
apple.spawn()
最终结果?
希望这有帮助!