Day 6 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Procrastination with Physics

Some days you want to want to stare at a screen watching a heap of random Christmas presents pile up under a poorly-rendered tree, and some days you want to learn how to drive a Javascript physics engine. With Python. In a browser. For me, today was both of those days.

Honestly, it’s a bit of a stretch even calling this a game, but it sure is mesmerising. I definitely didn’t spend a whole afternoon staring at it instead of writing this post, oh no. You can even click on it to add more presents!

First thing’s first, here’s the link to the app:

I used the awesome Matter.js physics engine to do the heavy lifting (dropping?) here, and the anvil.js module to drive it directly from Python. To keep things simple, everything you see is rendered by the physics engine - the white pins and the pot are static bodies, the tree is made up of several static bodies with collisions disabled, and the presents are random rectangles which collide with the pins, pot, and each other. And that’s it!

Here’s an example of creating a random present when the canvas is clicked:

  def canvas_mouse_down(self, x, y, button, **event_args):
    Matter.Composite.add(, [
      Matter.Bodies.rectangle(x, 0, randint(12,30), randint(12,30), {
        "angle": random()*pi*2,
        "render" : {
          "strokeStyle": "#fff",
          "lineWidth": 2

Check out the full source code here, and have a go at customising the game:

Or just stare at it some more. I won’t judge.

Give the Gift of Python

Share this post: