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)
: number and
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
const gameInterval: NodeJS.Timer = setInterval( () => moveSnake(game.direction), movementDelay );
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
You can probably guess what
moveSnake(game.direction) does. It moves the snake on the game board in the direction of
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?
gameOver === false, we clear
if (gameOver) clearInterval(gameInterval); //on unmount clear interval return () => clearInterval(gameInterval);
clearInterval on unmounting (refresh the browser, etc).
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
You can read about the useEffect Hook here.
In so many words,
setInterval is creating side effects and needs to wrapped in
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!