1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| """ 天体运行 二维平面模拟 2020年9月24日 by littlefean """ import turtle from random import randint
def main(): dt = 1 Earth = Planet("earth") Sun = Planet("sun") turtle.goto(Sun.loc) turtle.pendown() for i in range(10): turtle.goto(Sun.loc[0] + randint(1, 5), Sun.loc[1] + randint(1, 5)) Earth.loc = (150, 0)
turtle.penup() turtle.goto(Earth.loc) turtle.pendown()
Earth.v = (0, 0.5) Earth.m = 4
Sun.m = 5
while True: Earth.force = (( f(Earth, Sun) * ((Sun.loc[0] - Earth.loc[0]) / r(Earth.loc, Sun.loc)), f(Earth, Sun) * ((Sun.loc[1] - Earth.loc[1]) / r(Earth.loc, Sun.loc)) ))
Earth.a = (( Earth.force[0] / Earth.m, Earth.force[1] / Earth.m )) Earth.v = (( Earth.v[0] + Earth.a[0] * dt, Earth.v[1] + Earth.a[1] * dt, )) Earth.loc = (( Earth.loc[0] + Earth.v[0] * dt, Earth.loc[1] + Earth.v[1] * dt )) turtle.goto(Earth.loc[0], Earth.loc[1])
class Planet: """ 星球类 默认位置,速度矢量,加速度矢量,均为 (0, 0) """
def __init__(self, name): self.name = name self.loc = (0, 0) self.v = (0, 0) self.a = (0, 0) self.m = 5e10 self.force = (0, 0)
def __str__(self): return f"x:{self.loc[0]},y:{self.loc[1]}"
__repr__ = __str__
def r(locationA, locationB): """ 计算两点之间的位置 :param locationA: A点的位置 :param locationB: B点的位置 :return: AB之间的距离 """ x1, y1 = locationA x2, y2 = locationB distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 return distance
def f(planetA, planetB): """ 计算AB星球之间的万有引力,返回力的数值 :param planetA: :param planetB: :return: """ G = 9.8 force = G * planetA.m * planetB.m / r(planetA.loc, planetB.loc) ** 2 return force
if __name__ == '__main__': main()
|