# Program Name: create_and_download_pyfile.ipynb
# Creation Date: 20251015
# Overview: Create a Python file (.py) in Google Colab and download it automatically
# Usage: Run in Google Colab → generates collision_vpython.py and downloads it
from google.colab import files
# ==== 保存したいPythonコード / Python code content ====
code = """# Program Name: collision_vpython.py
# Creation Date: 20251015
# Overview: Simulate 1D elastic collision between two balls using VPython
# Usage: Run in VS Code terminal → python collision_vpython.py
from vpython import sphere, vector, rate, color, scene
m1, m2 = 2.0, 1.0
v1, v2 = 2.0, -1.0
r1, r2 = 0.5, 0.5
dt = 0.005
x1_init, x2_init = -4.0, 4.0
scene.background = color.white
scene.width = 800
scene.height = 400
scene.center = vector(0, 0, 0)
scene.title = "1D Elastic Collision Simulation"
ball1 = sphere(pos=vector(x1_init, 0, 0), radius=r1, color=color.blue, make_trail=True)
ball2 = sphere(pos=vector(x2_init, 0, 0), radius=r2, color=color.red, make_trail=True)
v1_vec = vector(v1, 0, 0)
v2_vec = vector(v2, 0, 0)
while True:
rate(200)
ball1.pos += v1_vec * dt
ball2.pos += v2_vec * dt
if abs(ball1.pos.x - ball2.pos.x) <= (r1 + r2):
v1_new = ((m1 - m2) / (m1 + m2)) * v1_vec.x + (2 * m2 / (m1 + m2)) * v2_vec.x
v2_new = ((2 * m1) / (m1 + m2)) * v1_vec.x + ((m2 - m1) / (m1 + m2)) * v2_vec.x
v1_vec.x, v2_vec.x = v1_new, v2_new
if abs(ball1.pos.x) > 6:
v1_vec.x *= -1
if abs(ball2.pos.x) > 6:
v2_vec.x *= -1
"""
# ==== ファイル作成 / Write file ====
filename = "collision_vpython.py"
with open(filename, "w", encoding="utf-8") as f:
f.write(code)
# ==== ダウンロード実行 / Download file ====
files.download(filename)
使い方
-
上記を
save_python_file.pyなどの名前で保存。 -
実行:
python save_python_file.py -
同じフォルダに
collision_vpython.pyが生成されます。 -
その中身を変更したい場合は、
code = """ ... """の中に任意のPythonコードを書けばOKです。