Game Programming with JavaScript, HTML and CSS: Introduction

This is the first part of a series of tutorials that aim to teach you how to make games with JavaScript, HTML and CSS. In this tutorial you will learn the concept of the Game Loop and will apply this concept to build a simple animation. HTML, JavaScript and CSS are normally used to design web pages. However, after finishing this tutorial you will understand how these 3 tools can be combined to make games. The video below shows what you will accomplish at the end of the tutorial.

What you will need:

  • A browser to test the concept.
  • Any editor of your choice to write the code.

Here is the link to the Complete Source Code.

The HTML Structure

When writing a game using HTML you first start coding the HTML structure.

<html>
<head>
  <title>Game Programming with JavaScript, HTML and CSS: Introduction</title>

  <style type='text/css'>
    #game_region {
      width: 600px;
      height: 400px;
      background-color: black;
      position:relative;
    }

    #box {
      width: 48px;
      height: 48px;
      background-color: white;
      position: absolute;
      left: 280px;
      top: 180px;
    }
  </style>
</head>
<body>
  <div id='game_region'>
    <div id='box'></div>
  </div>
</body>
</html>

Save this code in a file and run it on a browser. You should have as a result a black region with a small white box inside it. The black region is where the animation will run and is defined by the game_region div. The white box is the one that will be animated and is defined by the box div inside the game_region div.

The Game Loop

The Game Loop is one of the fundamentals elements of a game. It is a loop where the game actually happens. It is a series of instructions that are repeated until an event triggers the end of the game. We summarize what a game loop is in the pseudo-code presented below.

  while( game_is_running ) {
    check_input()     // keyboard, mouse, joystick
    update_objects()  // according to input or AI (artificial intelligence)
  }

Each iteration of the game loop is called a frame. When designing a game loop we must make sure each frame takes exactly the same time on any machine. This is to avoid the game to run at different speeds depending on the speed of the machine. To have a smooth animation the game loop must run at least at 30 frames per second. So, how do we create a game loop using JavaScript? We create it using the setInterval() function. This function makes a given function to be called in given periodic intervals. The interval period is given in milliseconds.

  setInterval(func,interval);
  // The function func will be called infinitely every "interval" milliseconds

Let us create a game loop that runs at 30 FPS. 1 second is equivalent to 1000 milliseconds. So one frame should take 1000/30=33 milliseconds. The code below shows how we create this loop:

  function gameLoop() {
    // ...
  }

  setInterval(gameLoop, 33);

The animation

So below is the complete code to animate the box. This is the HTML structure we already have plus the JavaScript code to animate the box.

<html>
<head>
  <title>Game Programming with JavaScript, HTML and CSS: Introduction</title>

  <style type='text/css'>
    #game_region {
      width: 600px;
      height: 400px;
      background-color: black;
      position:relative;
    }

    #box {
      width: 48px;
      height: 48px;
      background-color: white;
      position: absolute;
      left: 280px;
      top: 180px;
    }
  </style>

<script type='text/javascript'>
    var box;

    // Maximum value for the box's X and Y coordinates.
    var MAX_BOX_X = 600 - 48;
    var MAX_BOX_Y = 400 - 48;

    var SPEED = 5;

    // Configures the init() function to be called after the document is loaded.
    window.onload = init;

    function init() {
      box = document.getElementById("box");

      box.posX = box.offsetLeft;
      box.posY = box.offsetTop;
      box.velX = SPEED;
      box.velY = SPEED;

      setInterval(gameLoop,33);
    }

    function gameLoop() {
      moveBox()
    }

    function moveBox() {
      box.posX += box.velX;
      box.posY += box.velY;

      if( box.posX <= 0 ) {
        box.posX = 0;
        box.velX = -box.velX;
      }
      if( box.posX >= MAX_BOX_X ) {
        box.posX = MAX_BOX_X;
        box.velX = -box.velX;
      }
      if( box.posY <= 0 ) {
        box.posY = 0;
        box.velY = -box.velY;
      }
      if( box.posY >= MAX_BOX_Y ) {
        box.posY = MAX_BOX_Y;
        box.velY = -box.velY;
      }
      // Update the left and top CSS properties.
      box.style.left = box.posX +  "px";
      box.style.top  = box.posY + "px";
    }
  </script>
</head>
<body>
  <div id='game_region'>
    <div id='box'></div>
  </div>
</body>
</html>

The constant MAX_BOX_X defines the maximum value the box’s left property can have while still being completely inside the game_region div. Likewise, The MAX_BOX_Y defines the maximum value for the box’s top property. SPEED defines the box’s moving speed. The animation is run only after the document is completely loaded. In the init() function we save the reference to the box div in the box variable. We later use this variable to change the box’s position. Next we create the properies box.posX and box.posY where we save the box’s coordinates. obj.offsetLeft and obj.offsetTop are read-only properties that return, respectively, the left and top box coordinates. We follow creating the velocity properties. The function ends setting up the game loop to run at 30 FPS.

In the game loop we just call the moveBox() function that moves the box in each frame. In the moveBox() function we update the box position according to the velocity properties and we make sure the box stays inside the game_region. When the box hits the game_region boundaries we make it bounce by inverting the respective velocity property. To make the box position change in the screen we update the left and top CSS positioning properties using box.style.left and box.style.top.

box.offsetLeft ==> Returns the box's x coordinate (it is read-only)
box.offsetTop  ==> Returns the box's y coordinate (it is read-only)
box.style      ==> Gives access to the CSS properties
box.style.left ==> Gives access to the CSS left property
box.style.top  ==> Gives access to the CSS top property

Exercises

  1. Modify the background color of the moving box from white to yellow.
  2. Modify the game loop to run at 40 FPS.
  3. Modify the code to have 2 animated boxes.

If you enjoy making games like we do, then subscribe to this blog and/or follow us on twitter.

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.