DEV Community

Cover image for Browser game with React
Kailash Sankar
Kailash Sankar

Posted on

Browser game with React

As a weekend project, I decided to try something fun with react like building a mini browser game. And the outcome isn't too bad - void-dodge

This post will briefly describe how it was done without going into the code, the source code can be viewed here


Obstacle dodge games like flappy bird seemed relatively easy to try. Adding a space theme and making it vertical, we would have an area with a space ship moving left and right and asteroids sliding down.

|    AA  A |
|          |
| AAA   AA |
|          |
| <- S ->  |
|          |
Enter fullscreen mode Exit fullscreen mode

Imagine the area of the game is like a grid, asteroid and ship occupy cells within it. Asteroid cells are rendered from the top of the grid and move down with time and at some point it will be in the same row as the ship, if A and S occupy the same cell then it's game over otherwise we bump up the score.


I considered the cell size as 64px

Playground: A box of 706 x 512 with a border, this will be the container of the game

Ship: A 64x64 cell, placed slightly below the middle of the playground. The ship will only move left and right,

Asteroid belt: A row with 8 cells, there will be two types here. Filled cells which represent objects and empty cells for the ship to pass through.


The asteroid belt is generated by picking a few random indexes to keep as empty and marking the rest as filled.

The left pixel position of the cells which are filled out is kept in an array. When the belt is horizontally aligned with the ship and if it's current left position is contained within this array then we have a collision.

The belt is generated outside of the playground area, animated by CSS, and then removed once it passes through. The belts are maintained as a queue - a belt added and one removed every 2 seconds by an interval code.

The collision checks are run by another interval code every ~100ms, inefficient but does not affect a game this tiny considering we only have at max 4-5 instances of the belts active at a time.

I used the redux store to maintain the game state, score, and the final summary info. The game state can have three values - intro, game in-progress, and game over. The score is persisted on to localStorage, keeping the most recent 5 and also the top score.

I added react-particles-js and some retro music to make the environment more engaging and icons from icon finder to get the space theme.

That's all folks :)

Top comments (1)

bhansa profile image
Bharat Saraswat

Cool! 🎉👏