其他用户发布的方法效果很好。然而,我用面向对象的设计做了一个类似的太阳系模型,我所做的是创建一个名为 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()
然后,我创建了一个 Planet 类,并制作了行星代理,并在 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 #make planet an agent
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
#MAKE PLANET
self._turtle = turtle.Turtle(shape = 'circle')
self._turtle.hideturtle()
#INITIALIZE PLANET
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()
这实现了您的目标,并且还可以通过调用 Planet Class 来更轻松地稍后添加具有您希望它包含的特定参数的另一个行星,而不是绘制一个全新的行星并尝试单独将其与其他行星一起移动.
希望这对某人有所帮助!