One Hour Pong

I’ve been teaching my nephew to code for the past few years and we did a game jam together over the winter break. He said to me: “Uncle Josh, you sure can code fast.” I reminded him that I’ve been programming for 30+ years, and one day he’ll be even better than I am.

My nephew struggles to come up with ideas and often goes down rabbit holes on one feature or tool instead of working on the rest of the game. I told him that time constraints can make a game better because it forces you to focus. Ever the clever child, he suggested I do a pong game in one hour. From scratch. With no existing code or game frameworks. Challenge accepted!

Here’s what I built last Tuesday.

z

Live Demo

Construction

To build the game I first spent about 15 min doing setup. Point and Bounds classes. Ball, Paddle, Game state. And of course a game loop with functions for input, collisions, draw, check for game over. However, I didn’t actually write these functions or classes yet. I just stubbed in the names and left the implementations for later. My nephew asked why I was doing it this way. “Having the stubs helps to organize your brain and your code. I’ll fill in the code as I need it. That way you don’t wast time building parts that you don’t end up needing.”

By the 20 minute mark I had basic drawing working, and movement with keyboard inputs by 25 min. Collisions and physics ended up being the hardest part. I wrote a Bounds class with an intersection method, but that wasn’t enough. To do collisions correctly the direction of the ball's motion matters. I ended up doing a more brute force method where I check the ball against the bottom of the top wall, the top of the bottom wall, each paddle, etc. Not as clean as I’d like, but far simpler.

I managed to add sound and fade effects in the last 5 min. With 30 seconds remaining I remembered I still needed to make it "pretty", which ended up being just changing colors to a clean grayscale with red for the ball.

Once the challenge was over I did spend another 20 minutes fixing the fading code. It worked before but was wrong. I also tweaked the size of the canvas, added wall bumpers, and a click event to trigger audio. (I always forget that part).

What you see above is with the extra 20 min.

Tools used:

  • Typescript. Using Typescript with a good IDE (WebStorm) can be magical.
  • For sound effects I used the JSFXR web tool and embedded it in the game using a string encoding instead of downloading wave files.
  • I started using BeepBox to create a music composition for the background, but ran out of time. You can hear the little bit I managed to make here.

Conclusion.

Doing a one hour game was really fun. The time constraint pushed me to think fast and balance planning with YAGNI. I’m really impressed with how far you can get with modern canvas and javascript, no frameworks required.

You can view the soruce here.

Talk to me about it on Twitter

Posted January 12th, 2023

Tagged: game javascript