Skip to content
Programming contents

Lesson 2.8: Project: publish your game

The game from 1.14, on a website with your name. With everything from this stage: files, terminal, editor, Git and GitHub.

The idea

The game from 1.14 lived in the console. Now it gets its own page, with a button to play, and an address you can send to anyone.

Two files:

  • game.js: the game, inside a function.
  • index.html: the page, with the button that calls it.

The game, in a function

Create game.js. It's the game from 1.14, with the Cancel fix, inside a function play():

JavaScript
function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function play() {
  const secret = random(1, 100);
  let attempts = 0;
  let attempt = 0;

  while (attempt !== secret) {
    const answer = prompt("Guess the number (1-100):");

    if (answer === null) {
      break;
    }

    attempt = Number(answer);
    attempts = attempts + 1;

    if (attempt < secret) {
      alert("Higher");
    } else if (attempt > secret) {
      alert("Lower");
    }
  }

  if (attempt === secret) {
    alert("You got it in " + attempts + " attempts!");
  }
}

Being in a function, the game doesn't start on its own: it starts when someone calls play(). And each round has its own variables, so you can play again without reloading.

The page

Replace the index.html from 2.7 with this one:

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Guess the number</title>
  </head>
  <body>
    <h1>Guess the number</h1>
    <p>I've picked a number from 1 to 100.</p>
    <button onclick="play()">Play</button>

    <script src="game.js"></script>
  </body>
</html>
  • script loads game.js into the page.
  • onclick="play()" calls the function when the button is pressed.

Testing and publishing

  1. Double-click index.html and play a round.
  2. If it works, upload it:
Terminal
git add .
git commit -m "feat(game): add the game"
git push

GitHub Pages was already switched on in 2.7: in a couple of minutes, the game is at https://YOUR-USERNAME.github.io/my-game/.

Try it

Exercise

On a branch, change the game so it goes from 1 to 1000. Join it into main, push it and check the website.

Show the solution
Terminal
git switch -c up-to-1000

In game.js, two changes: random(1, 1000) and the prompt() text, which now says "(1-1000)". In index.html, the paragraph. Save and:

Terminal
git add .
git commit -m "feat(game): extend the range up to 1000"
git switch main
git merge up-to-1000
git push

Summary

  • A function makes the game start when you say so.
  • script loads the JavaScript into the page; onclick calls it from a button.
  • Test locally, commit, push: and the website updates.
  • You have a published game, with its history, in a repository of your own.