What is a Game Loop?

Learn about the concept of a game loop and build a simple square oscillator game.

What is a game loop?

Building a game is an exciting topic, but at the same time, it can become too complex to develop high-end games. Since our focus will primarily be on using data structures and different algorithms to build small but real-world games, in this course, it becomes essential to know the basics of developing a game. Generally, while developing any game, there is an important concept called game loop.

A game loop is a loop that keeps on executing unless the user exits the game or the game is over. There are usually three steps involved in any game loop.

Let's talk about each of the them below:

  1. Initialization: The initialization logic is executed whenever a game is loaded. All of the initialization-related logic for the game needs to be executed in this step. Written under this step is usually any logic that only needs to be executed once, at the start of the game.

  2. Loop: The loop is executed forever, until the user stops the game or the game ends. Inside this loop, two significant logics need to be implemented. Both these logics work together to serve a frame. A frame is nothing but one iteration of the game loop.

    1. Draw: This logic will contain the code that will generate new graphics in the game based on the conditions.

    2. Update: This logic will contain the code that will update configurations like the player's score, the number of lives left, etc.

  3. Exit: This contains the logic that needs to be executed when the game is going to stop. Usually, it happens when the user has exited the game or the game is over. It can contain the logic to display the leaderboard, the player's score, etc.

That's enough theory. Now let's build an elementary game loop and see how it works.

Build a game loop to oscillate a square vertically

We are going to build an elementary game loop and perform the following operations:

  1. Create a canvas object and display it on HTML.

  2. Display a red square and oscillate it within the canvas vertically.

  3. After 30 oscillations, end the game. The game loop will stop and a message will be displayed below the canvas.

First, let's look at the final output that will be generated.

Get hands-on with 1200+ tech skills courses.