Game Programming with JavaScript, HTML and CSS: keyboard input

In the last tutorial we covered the concept of the game loop and applied it to make a simple animation. Drawing upon the code of the last tutorial, we will add a box that we will be controlled using the keyboard. After you finish this tutorial you will see how easy it is to add keyboard input to your games.

Click here to see what you will accomplish in this tutorial.

What you will need:

  • Any text editor of your choice.
  • A browser to run the code.

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;
    }

    #help {
      font-size: 16px;
      font-weight: bold;
      padding: 10px;
      color: green;
    }

    #keyb_box {
      width: 64px;
      height: 16px;
      background-color: yellow;
      position: absolute;
      left: 200px;
      bottom: 15px;
    }
  </style>
</head>
<body>
  <div id='game_region'>
    <div id='box'></div>
    <div id='keyb_box'></div>
  </div>
  <p id='help'>USE THE LEFT AND RIGHT KEY ARROWS TO MOVE THE YELLOW BOX</p>
</body>
</html>

Save this code and run it on a browser. You should see a black region with one white box and yellow box inside like what is seen in the screenshot below. Our goal in this tutorial is to move the yellow box according to input received from the keyboard. The white box will be animated with code borrowed from the last tutorial.

Handling Input

When capturing keyboard input we must know in advance which keys we want to capture. In this tutorial we will use the LEFT and RIGHT arrow keys to move the yellow box. To handle input we hook the keydown and keyup events using JavaScript. When these events are fired they pass an event parameter that give us the key code of the pressed or released key. So, we must know the key codes of the keys we want to capture. Below I have listed some key codes. You can find more key codes by googling for “JavaScript Key Codes”.

backspace 	8
tab 	        9
enter 	        13
shift 	        16
ctrl 	        17
alt 	        18
caps lock 	20
escape 	        27
page up 	33
page down 	34
end 	        35
home 	        36
left arrow 	37
up arrow 	38
right arrow 	39
down arrow 	40

Below I show how to hook the keydown and keyup events to capture when the LEFT and RIGHT arrow keys are pressed/released.

  // These are flags that will tell us the state of the LEFT and RIGHT arrow keys.
  var keyLeft;
  var keyRight;

  document.onkeydown = keyDown;
  document.onkeyup = keyUp;

  function keyDown(e) {
    // Internet Explorer passes the event object in window.event
    if( !e ) {
      e = window.event;
    }
    if( e.keyCode == 37 ) {
      keyLeft = true;
    }
    else if( e.keyCode == 39 ) {
      keyRight = true;
    }
  }

  function keyUp(e) {
    // Internet Explorer passes the event object in window.event
    if( !e ) {
      e = window.event;
    }
    if( e.keyCode == 37 ) {
      keyLeft = false;
    }
    else if( e.keyCode == 39 ) {
      keyRight = false;
    }
  }

First, we set the functions keyDown() and keyUp() to handle the keydown and keyup events. When a key is pressed the keydown event is fired and the keyDown() function is called. In the keyDown() function we check if the key is the LEFT or RIGHT arrow key and set the corresponding flag if true.

When a key is released the keyup event is fired and the keyUp function is called. In the function we check if the key  is the LEFT or RIGHT arrow key and reset the corresponding flag if true.

Next we modify the code from the last tutorial to add input handling. See the code below.

<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;
    }

    #help {
      font-size: 16px;
      font-weight: bold;
      padding: 10px;
      color: green;
    }

    #keyb_box {
      width: 64px;
      height: 16px;
      background-color: yellow;
      position: absolute;
      left: 200px;
      bottom: 15px;
    }
  </style>

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

    var keyLeft;
    var keyRight;

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

    var SPEED = 5;

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

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

      document.onkeydown = keyDown;
      document.onkeyup = keyUp;
      keybBox.posX = keybBox.offsetLeft;
      keybBox.posY = keybBox.offsetTop;

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

      setInterval(gameLoop,33);
    }

    function keyDown(e) {
      // Internet Explorer passes the event object in window.event
      if( !e ) {
        e = window.event;
      }
      if( e.keyCode == 37 ) {
        keyLeft = true;
      }
      else if( e.keyCode == 39 ) {
        keyRight = true;
      }
    }

    function keyUp(e) {
      // Internet Explorer passes the event object in window.event
      if( !e ) {
        e = window.event;
      }
      if( e.keyCode == 37 ) {
        keyLeft = false;
      }
      else if( e.keyCode == 39 ) {
        keyRight = false;
      }
    }

    function gameLoop() {
      handleInput();
      moveBox();
    }

    function handleInput() {
      if( keyLeft ) {
        keybBox.posX -= 5;
        if( keybBox.posX < 0 ) {
          keybBox.posX = 0;
        }
      }
      if( keyRight ) {
          keybBox.posX += 5;
          if( keybBox.posX >= MAX_KEYBBOX_X ) {
            keybBox.posX = MAX_KEYBBOX_X;
          }
      }
      keybBox.style.left = keybBox.posX + "px";
    }

    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 id='keyb_box'></div>
  </div>
  <p id='help'>USE THE LEFT AND RIGHT KEY ARROWS TO MOVE THE YELLOW BOX</p>
  <a href='http://codentronix.com/?p=100'>Click here</a> to see the tutorial.
</body>
</html>

Click here to see the code in action.

We modified the init() function adding code to hook the keydown and keyup events. We also get the reference to the yellow box (defined by the keyb_box div).

The game loop was modified to call the handleInput() function.  So in each frame we will check if the LEFT or RIGHT arrow key is pressed and move yellow box accordingly. The white box is moved regardless of the presence of any input.

Conclusion

To add keyboard input we hook the keydown and keyup events and declare variable flags for each key we want to capture. When a key that interests us is pressed we set the corresponding key flag in the keydown event. Likewise, when a key that interests us is released we reset the corresponding flag in the keydown event. In the game loop we use the key flags we update in the keydown and keyup events.

Exercise

Modify the code to move the yellow box up and down using the UP and DOWN arrow keys.

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

  1. система приема платежей и партнерских программ – сервис приема платежей, платежная система прием платежей.

Leave a Comment

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