Using a Gutenberg Block to run Snake

TL:DR I made Snake in React and it runs in a Gutenberg editor block. Try it out in one click on WordPress Playground.

The code is of course open source and available over at my Github. The actual Snake game is adapted from MaelDrapier’s React Simple Snake, and whilst that is even available on NPM, I wanted to Fork the code and make some tweaks so that it would run better in Gutenberg.

The original React Simple Snake uses a recursive function to handle the main game loop, a timer that re-calls itself each time it completes. For my implementation instead I use a frame counter that increases each time the timer completes, and then useEffect() to monitor changes in that frame counter and re-call the timer function. It’s a small tweak but it forces a re-render of the block at the expected timing.

I also migrated the high score system away from JS LocalStorage and instead moved it directly onto a block attribute. That means whenever your score exceeds a high score, the post editor becomes dirty and is ready to save your changes. Using attributes like this on the block also means I have a simple way of offering game options, like colours, text styling etc. really simply.

The game needs work, the code needs work and linting, but this MVP is pretty fun. Add the block to your post editor whenever you want to play Snake, and if you save the post, don’t worry, nothing renders to the front-end!

I did this mainly to test a few things:

  • Could WordPress Playground reasonably be used as a game distribution service?
  • Could Gutenberg blocks be used for gaming, or fun things in general.

The answer to both is yes! This is something I’d like to keep pushing at, keep making WordPress weird and just generally fun.

2 responses to “Using a Gutenberg Block to run Snake”

  1. […] Rodes is Using a Gutenberg Block to run Snake. He built it in React and runs it in the Gutenberg editor. It’s a fabulous way to […]

    Like

Leave a comment