Today we'll use the canvas to build another HTML5 game.

The architecture behind how games are built inspired React which we'll be learning in a few weeks. One amazing thing about computer science is how many problems can be solved in similar ways.

What You'll Learn

Examples

Links

Required Features

function randomlyPlace(axis) {
  if (axis === "x") {
    return Math.floor(Math.random() * canvas.width + 1);
  } else {
    return Math.floor(Math.random() * canvas.height + 1);
  }
}
monster.x = randomlyPlace("x");
monster.y = randomlyPlace("y");

Your technical lead is good but he could have been better. Name the expected behavior of the expression for the benefit of future developers.

const monsterCaughtByHero =
  hero.x <= monster.x + 32 &&
  monster.x <= hero.x + 32 &&
  hero.y <= monster.y + 32 &&
  monster.y <= hero.y + 32;
if (monsterCaughtByHero) {
  monster.x = randomlyPlace("x");
  monster.y = randomlyPlace("y");
}

Our webapp/game has state. Is the user signed in? How many monsters did the hero catch? Where is the hero? And much more...

We can easily structure this state using an object.

const applicationState = {
  isGameOver: false,
  currentUser: "PrimeTimeTran",
  highScore: {
    score: 22,
    user: "PrimeTimeTran",
    date: "Thu Oct 02 2019 15:11:51 GMT+0700",
  },
  gameHistory: [
    { user: "Duc", score: 19, date: "Thu Sep 03 2019 15:11:51 GMT+0700" },
    { user: "Huy", score: 18, date: "Thu Oct 03 2019 15:11:51 GMT+0700" },
    { user: "Chloe", score: 21, date: "Thu Oct 01 2019 15:11:51 GMT-6000" },
  ],
};
const applicationState = {
  isGameOver: false,
  currentUser: null,
  highScore: {
    score: 0,
    user: null,
    date: null,
  },
  gameHistory: [{ user: null, score: 0, date: null }],
};

Positive : Use localStorage to persist scores across browser refreshes.

Deploy

|- week2-friday-game/
  |-- ...
  |-- ...