starcore-explorer-bad/content/pyodide/pyb2d/newtons_cradle.ipynb

131 lines
3.6 KiB
Plaintext
Raw Normal View History

2023-06-24 01:19:43 +08:00
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "82ae535a-a041-40f0-8c40-e689b894b0bc",
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"if \"pyodide\" in sys.modules:\n",
" import piplite\n",
" await piplite.install('pyb2d-jupyterlite-backend>=0.4.0')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7381ff66-7924-4216-b141-8f7b15ed038a",
"metadata": {},
"outputs": [],
"source": [
"from b2d.testbed import TestbedBase\n",
"import b2d\n",
"\n",
"\n",
"class NewtonsCradle(TestbedBase):\n",
"\n",
" name = \"newton's cradle\"\n",
"\n",
" def __init__(self, settings=None):\n",
" super(NewtonsCradle, self).__init__(settings=settings)\n",
"\n",
" # radius of the circles\n",
" r = 1.0\n",
" # length of the rope\n",
" l = 10.0\n",
" # how many balls\n",
" n = 10\n",
"\n",
" offset = (l + r, 2 * r)\n",
" dynamic_circles = []\n",
" static_bodies = []\n",
" for i in range(n):\n",
" if i + 1 == n:\n",
" position = (offset[0] + i * 2 * r + l, offset[1] + l)\n",
" else:\n",
" position = (offset[0] + i * 2 * r, offset[1])\n",
"\n",
" circle = self.world.create_dynamic_body(\n",
" position=position,\n",
" fixtures=b2d.fixture_def(\n",
" shape=b2d.circle_shape(radius=r * 0.90),\n",
" density=1.0,\n",
" restitution=1.0,\n",
" friction=0.0,\n",
" ),\n",
" linear_damping=0.01,\n",
" angular_damping=1.0,\n",
" fixed_rotation=True,\n",
" )\n",
" dynamic_circles.append(circle)\n",
"\n",
" static_body = self.world.create_static_body(\n",
" position=(offset[0] + i * 2 * r, offset[1] + l)\n",
" )\n",
"\n",
" self.world.create_distance_joint(\n",
" static_body,\n",
" circle,\n",
" local_anchor_a=(0, 0),\n",
" local_anchor_b=(0, 0),\n",
" max_length=l,\n",
" stiffness=0,\n",
" )\n",
"\n",
" static_bodies.append(static_body)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "6f694d32-8b23-40cf-91c3-0edd6abb658d",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b24ad88f6cfd4db19fc3145000e79635",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from pyb2d_jupyterlite_backend.async_jupyter_gui import JupyterAsyncGui\n",
"s = JupyterAsyncGui.Settings()\n",
"s.resolution = [1000,300]\n",
"b2d.testbed.run(NewtonsCradle, backend=JupyterAsyncGui, gui_settings=s);"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}