Amit Mehta
Indepth JavaScript

Follow

Indepth JavaScript

Follow
How to Create a Simple Game Loop in React, JavaScript/TypeScript in Under 10 Lines of Code

How to Create a Simple Game Loop in React, JavaScript/TypeScript in Under 10 Lines of Code

A super fun way to sharpen your front end development skills

Amit Mehta's photo
Amit Mehta
ยทJul 11, 2022ยท

2 min read

I recently coded up a few classic games with React, TypeScript, and CSS Grid: Minesweeper - Retro Style and Snake.

Why the heck would I use React and TypeScript to make a game? To sharpen employable job skills! ๐Ÿ˜‚

Creating a game is a super fun way to improve your front end development skills and show you really know how to manipulate the DOM. If you're new to programming, I definitely recommend a simple game project.

You can code up Minesweeper or Snake in just a few 100 lines of code.

Got it! Now, How do I Create a Game Loop?

Here's a snapshot right from VS Code... (if you don't understand it, no sweat, I'll walk you through it in a second)

game-loop-typescript-react

This is in TypeScript. Do not freak out if you don't know TypeScript. It's just static typing + JavaScript. If you remove : number and : NodeJS.Timer from the above code, then it becomes 100% JavaScript.

Let's go through this code from the top

const movementDelay: number = Math.round(1000 / game.snakeSpeed);

Here we're just determining how often our game loop will refresh. We do this by dividing 1000 milliseconds (1 second) by the game.snakeSpeed. Faster the snake speed, the smaller the movementDelay, the faster the game loop will refresh.

Next, we set up setInterval...

const gameInterval: NodeJS.Timer = setInterval(
      () => moveSnake(game.direction),
      movementDelay
    );

While gameInterval is active (not cleared), moveSnake(game.direction) will execute every movementDelay milliseconds. Remember setInterval(fn,time) executes the function fn you pass to it, every time milliseconds.

You can probably guess what moveSnake(game.direction) does. It moves the snake on the game board in the direction of game.direction.

On that point: It's really important to properly name your variables. It can make working on someone else's code a joy, versus a nightmare.

How do I stop the Game Loop?

Easy, when gameOver === false, we clear gameInterval:

    if (gameOver) clearInterval(gameInterval);

    //on unmount clear interval
    return () => clearInterval(gameInterval);

We also clearInterval on unmounting (refresh the browser, etc).

How does gameOver work?

It's a state variable I setup with a simple React useState hook:

const [gameOver, setGameOver] = useState<boolean>(false);

When the snake hits into itself or a wall then moveSnake(...) function, will setGameOver(true). This state change then triggers:

    if (gameOver) clearInterval(gameInterval);

Why is all the code wrapped in useEffect ?

You can read about the useEffect Hook here.

In so many words, setInterval is creating side effects and needs to wrapped in useEffect.

Hope this makes sense and gives you confidence to go out and build your own games. ๐Ÿ˜ธ

Did you find this article valuable?

Support Amit Mehta by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this