In the blog post What Can You Do With JavaScript I already explained you can build everything with it. And this includes browser games that I’m going to show in this tutorial.

Complete code for the game is 53 lines long so it should be easy to understand even for beginners.

The entire code is at the bottom of this post and every step is explained in little chunks.

JavaScript Game

The goal of the game is to click on the read square as quickly and as many times as possible.

The rules are simple:

  • red square randomly appears on the screen
  • every time you click on the screen the square changes its position
  • if you click on the square, you get a point
  • if you miss a square, you lose a point

This game can definitely trim your hand-eye coordination and can be source of a lot of fun. Especially if you play it with your friends under a time constraint.

Game Source Code

Here are the exact steps and explanations for every part of the code:

  1. HTML File
  2. Program Initialization
  3. Adding The Red Square Target
  4. Randomize Target Position
  5. Refresh The Screen
  6. Move Target On Click
  7. Keeping The Score
  8. Full Source Code

1) HTML File

Our entire code will be inside an HTML file. Specifically all you need are script tags:

<script>
  // all your code goes here
</script>

2) Program Initialization

We need to run our code but only after the browser is ready and all the code is loaded. If we try sooner we will probably have bugs.

The function that is called after the browser finishes loading is window.onload where window represents the browser. And the end result looks something like this:

const W = 1280; // canvas width
const H = 720; // canvas height

window.onload = function() {
  canvas = document.createElement('canvas');
  canvas.width = W;
  canvas.height = H;
  document.body.appendChild(canvas);
}

So after the code loads, we…

  • create HTML5 canvas object
  • set its size
  • add it to the HTML

If you’re wondering where does this document.body come from…

  • document represent entire HTML document
  • body is HTML tag inside that document

So even though we didn’t define any of these elements, the browser itself generated basic HTML code that looks like this:

<html>
  <head>
    <script> // your entire code here </script>
  </head>
  <body></body>
</html>

And that is why we “got away” with only defining <script></script> in our code. And we could add canvas to the body:

document.body.appendChild(canvas);

even though we didn’t define body anywhere.

3) Adding The Red Square Target

Just having an empty canvas is not enough. We need to make the canvas visible (black) as well as the target (red) we can click on:

ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = 'red';
ctx.fillRect(W/2, H/2, 30, 30);

Now the entire canvas is black, and the target square is positioned at the center of the canvas (having width and height of 30 pixels).

4) Randomize Target Position

We want the target to be at different positions every time we refresh the browser. And here is how we can get random x and y positions for our red square:

const x = Math.round(Math.random() * (W - 30));
const y = Math.round(Math.random() * (H - 30));

So after a little bit of cleaning up our code and defining variables for target position as well as target size, we have a code that looks like this:

const W = 1280; // canvas width
const H = 720; // canvas height
const targetSize = 30;
let targetPosition = {};

window.onload = function() {
  canvas = document.createElement('canvas');
  canvas.width = W;
  canvas.height = H;
  document.body.appendChild(canvas);
  setRandomPositionTarget();
  ctx = canvas.getContext('2d');
  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = 'red';
  ctx.fillRect(
    targetPosition.x, targetPosition.y,
    targetSize, targetSize
  );
}

function setRandomPositionTarget() {
  const x = Math.round(Math.random() * (W - targetSize));
  const y = Math.round(Math.random() * (H - targetSize));
  targetPosition = { x, y };
}

5) Refresh The Screen

Now this code will show the target at a different position on the canvas every time we refresh the browser. However, once the site is loaded we are no longer updating the screen.

And if we had a game that cannot update the screen would be very boring πŸ™‚

So that is what we have to do now.

First thing is to extract the drawing/refreshing of the screen from window.onload to a separate function:

function refreshScreen() {
  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = 'red';
  ctx.fillRect(
    targetPosition.x, targetPosition.y,
    targetSize, targetSize
  );
}

And then all you need to do is refresh the screen about 10 times per second. And we put this code at the end of window.onload function:

setInterval(refreshScreen, 1000/10);

6) Move Target On Click

Even though we implemented refreshing of the screen, nothing (visibly) happens on the screen. The red target square still sits at the same place after the screen loads.

To fix that, we need to change the position of the target when we do something. For example, when we click on the canvas.

First we add click detection on the end of window.onload function:

canvas.addEventListener('click', handleClick);

And then we define handleClick function that will set different position of the target every time this function is called:

function handleClick(ev) {
  setRandomPositionTarget();
}

And now every time we click on the canvas, the red target square moves to a new random location on the canvas.

7) Keeping The Score

The most important part of any game is the score. So we want to increase our score every time we click on the target by +1 and we want to decrease our score every time we miss the target by -1.

We will start by defining the score variable at the top of our code:

let scoreValue = 0;

Then we will create elements that will show the score at the bottom, below the canvas. We will put that code inside window.onload function:

scoreTitle = document.createElement('h1');
scoreTitle.innerText = 'Score:';
document.body.appendChild(scoreTitle);
score = document.createElement('h1');
score.innerText = 0;
document.body.appendChild(score);

And the actual updating of the score needs to be inside the handleClick function:

function handleClick(ev) {
  if (ev.offsetX < targetPosition.x || ev.offsetY < targetPosition.y) {
    scoreValue -= 1;
  }
  else if (
    ((targetPosition.x + targetSize) >= ev.offsetX) &&
    ((targetPosition.y + targetSize) >= ev.offsetY)
  ) {
    scoreValue += 1;
  } else {
    scoreValue -= 1;
  }
  score.innerText = scoreValue;
  setRandomPositionTarget();
}

And now we have full working game we created in JavaScript in only 53 lines of code. Further improvement ideas can include adding timeout timer. And when this timer reaches zero, score cannot be increased anymore.

Logic for that behavior can also be added in handleClick function.

Regardless, I wish you happy coding and experimenting with this game πŸ™‚

8) Full Source Code

<script>
  const W = 1280; // canvas width
  const H = 720; // canvas height
  const targetSize = 30;
  let targetPosition = {};
  let scoreValue = 0;

  window.onload = function() {
    canvas = document.createElement('canvas');
    canvas.width = W;
    canvas.height = H;
    document.body.appendChild(canvas);
    scoreTitle = document.createElement('h1');
    scoreTitle.innerText = 'Score:';
    document.body.appendChild(scoreTitle);
    score = document.createElement('h1');
    score.innerText = 0;
    document.body.appendChild(score);
    ctx = canvas.getContext('2d');
    setInterval(refreshScreen, 1000/10);
    setRandomPositionTarget();
    canvas.addEventListener('click', handleClick);
  }

  function refreshScreen() {
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, W, H);
    ctx.fillStyle = 'red';
    ctx.fillRect(targetPosition.x, targetPosition.y, targetSize, targetSize);
  }

  function setRandomPositionTarget() {
    const x = Math.round(Math.random() * (W - targetSize));
    const y = Math.round(Math.random() * (H - targetSize));
    targetPosition = { x, y };
  }

  function handleClick(ev) {
    if (ev.offsetX < targetPosition.x || ev.offsetY < targetPosition.y) {
      scoreValue -= 1;
    }
    else if (
      ((targetPosition.x + targetSize) >= ev.offsetX) &&
      ((targetPosition.y + targetSize) >= ev.offsetY)
    ) {
      scoreValue += 1;
    } else {
      scoreValue -= 1;
    }
    score.innerText = scoreValue;
    setRandomPositionTarget();
  }
</script>

P.S. -> read this article if you want toΒ double your salary

TAGS: how to make a web game with javascript, creating a game with javascript, make game with javascript, make games with javascript, games to make with javascript, making games with javascript tutorial, introduction game programming with javascript, how to make a game with html css and javascript, easy games to make with javascript, programming games with javascript, game design with html5 and javascript, how to make a video game with javascript, how to code a game with javascript, make a game with javascript and html5, create a game with javascript, creating games with javascript, how to make a simple game with javascript, can you make video games with javascript, how to make a browser game with javascript, how to create a game with javascript, create games with html5 and javascript, how to make games with javascript, game development with javascript, how to make a game with javascript, making a game with javascript, building games with javascript, can you make games with javascript, how to build a game with html css and javascript, making games with javascript, make a game with javascript, can you make a game with javascript, games in javascript with source code,