diff --git a/bodies/body.py b/bodies/body.py index bef3a6e33aed9d6211dd44a2e18e7aa8096e1ab9..7ee4055f6566c0d0f3318ed8030980f0b5d32471 100644 --- a/bodies/body.py +++ b/bodies/body.py @@ -353,7 +353,11 @@ class Body(metaclass=ABCMeta): with open(json_file, "r", encoding='utf-8') as read_content: json_data = json.load(read_content) for body_data in json_data["bodies"]: - # print(body_data) + try: + body_data = Body.exp(body_data) # print(body_data) + except Exception as e: + err_msg = f"{json_file} 格式错误:" + str(e) + raise Exception(err_msg) body = Body(**body_data) bodies.append(body) if "params" in json_data: @@ -361,6 +365,29 @@ class Body(metaclass=ABCMeta): # print(body.position_au()) return bodies, params + @staticmethod + def exp(body_data): + """ + 进行表达式分析,将表达式改为eval执行后的结果 + :param body_data: + :return: + """ + # + for k in body_data.keys(): + v = body_data[k] + if isinstance(v, str): + if v.startswith("$exp:"): + exp = v[5:] + body_data[k] = eval(exp) + elif isinstance(v, list): + for idx,item in enumerate(v): + if isinstance(item, str): + if item.startswith("$exp:"): + exp = item[5:] + v[idx] = eval(exp) + + return body_data + if __name__ == '__main__': # build_bodies_from_json('../data/sun.json') diff --git a/data/tri_bodies_sim_perfect_03.json b/data/tri_bodies_sim_perfect_03.json index be003294da2058f28ccad6f77db366834c3e74a8..2ac375f95269ec65902ce87a6db230ba2fdf2aba 100644 --- a/data/tri_bodies_sim_perfect_03.json +++ b/data/tri_bodies_sim_perfect_03.json @@ -5,11 +5,11 @@ "mass": 2e+30, "init_position": [ 0.0, - 518222240.0, + "$exp:math.sqrt(3) * 2 * AU", 0.0 ], "init_velocity": [ - -14.890000343322754, + -14.89, 0.0, 0.0 ], @@ -27,13 +27,13 @@ "name": "绿轨太阳B", "mass": 2e+30, "init_position": [ - -299195744.0, + "$exp: -2 * AU", 0.0, 0.0 ], "init_velocity": [ - 7.445000171661377, - -12.895118713378906, + "$exp: 1/2 * 14.88", + "$exp:-math.sqrt(3) / 2 * 14.88", 0.0 ], "density": 1408.0, @@ -50,13 +50,13 @@ "name": "蓝轨太阳C", "mass": 2e+30, "init_position": [ - 299195744.0, + "$exp: 2 * AU", 0.0, 0.0 ], "init_velocity": [ - 7.445000171661377, - 12.895118713378906, + "$exp: 1/2 * 14.88", + "$exp:math.sqrt(3) / 2 * 14.88", 0.0 ], "density": 1408.0, diff --git a/scenes/ursina_json_sim.py b/scenes/ursina_json_sim.py index d9e291c8495731612bf3975ebd336a36a2d402bc..254f3e4c93ea3000068e689dc35f14a610dc7348 100644 --- a/scenes/ursina_json_sim.py +++ b/scenes/ursina_json_sim.py @@ -13,7 +13,7 @@ from scenes.func import ursina_run if __name__ == '__main__': # TODO: 去掉注释,太阳演示 - bodies, params = Body.build_bodies_from_json('../data/sun.json') + # bodies, params = Body.build_bodies_from_json('../data/sun.json') # TODO: 去掉注释,太阳和地球演示 # bodies, params = Body.build_bodies_from_json('../data/sun_earth.json') # TODO: 去掉注释,在地球上看月相演示变化过程演示