其他用户发布的方法效果很好。然而,我用面向对象的设计做了一个类似的太阳系模型,我创建了一个名为System的类,在其中使用所需的高度和宽度来创建系统,并创建了一个名为stepAll的函数,该函数具有代理列表并将该列表中所有代理推进一步。
class System:
"""A two-dimensional world class."""
def __init__(self, width, height):
"""Construct a new flat world with the given dimensions."""
self._width = width
self._height = height
self._agents = { }
self.message = None
def getWidth(self):
"""Return the width of self."""
return self._width
def getHeight(self):
"""Return the height of self."""
return self._height
def stepAll(self):
"""All agents advance one step in the simulation."""
agents = list(self._agents.values())
for agent in agents:
agent.step()
然后,我创建了一个行星类,并将行星设为代理,定义了它们在Step函数中的步骤。
class Planet:
"""A planet object"""
def __init__(self, mySystem, distance, size, color, velocity, real_size, real_mass, name):
self = self
self._system = mySystem
mySystem._agents[self] = self
self._velocity = velocity
self._color = color
self._distance = distance
self._size = size
self._position = [distance, distance - distance]
self._angle = 90
self._real_size = real_size
self._real_mass = real_mass
self._name = name
self._turtle = turtle.Turtle(shape = 'circle')
self._turtle.hideturtle()
self._turtle.speed('fastest')
self._turtle.fillcolor(color)
self._turtle.penup()
self._turtle.goto(self._position)
self._turtle.turtlesize(size,size,size)
self._turtle.showturtle()
def getmySystem(self):
"""Returns the system the planet is in"""
return self._mySystem
def getdistance(self):
"""Returns the distance the planet is from the sun"""
return self._distance
def getposition(self):
"""Returns the position of the planet"""
return self._position
def getvelocity(self):
"""Returns the velocity of the planet"""
return self._velocity
def step(self):
"""Moves the planet one step on its orbit according to its velocity and previous position"""
xvar = self._position[0]
yvar = self._position[1]
newx = int(self._distance*math.cos(math.radians(90-self._angle)))
newy = int(self._distance*math.sin(math.radians(90-self._angle)))
self._turtle.goto(newx, newy)
self._angle = self._angle - self._velocity
然后在我的main()函数中,我使用它们各自的值初始化了所有行星,并说:
while True:
space.stepAll()
这样做可以实现你的目标,而且通过调用行星类来添加另一个具有特定参数的行星会更加容易,而不是绘制全新的行星并尝试单独移动它以及其他行星。
希望这能帮助到某些人!