Frontier Software

Robert Laing's programing notes

JSDoc

By Robert Laing

JSDoc

1. fetch images and sound files as promises

Using Promises

const images = {};

fetch("chess.json")
.then(response => response.json())
.then(data => {
  Object.keys(data.images).forEach(img => {
    images[img] = new Promise((resolve, reject) => {
      let image = new Image();
      image.src = data.images[img];
      image.addEventListener("load", () => resolve(image));
    });
  });
});

2. window.addEventListener(“DOMContentLoaded”, setup);


function setup(event) {
  initState();
  resizeListener(null);
  window.requestAnimationFrame(animationLoop);
}

window.addEventListener("DOMContentLoaded", setup);

3. initState() and resizeListener(null);


/**
 * The resizeListener event handler
 * @function resizeListener
 * @returns {undefined} Mutates the scale attribute of
 */
function resizeListener(event) {
  const oldScale = state.scale;
  state.scale = getScale(BASE_WIDTH, BASE_HEIGHT);
  canvas.width = state.scale * BASE_WIDTH;
  canvas.height = state.scale * BASE_HEIGHT;
  state.width = canvas.width;
  state.height = canvas.height;
  scaleText(state.scale);
  state.sprites.forEach(function (sprite) {
    sprite.xCentre *= state.scale/oldScale;
    sprite.yCentre *= state.scale/oldScale;
    sprite.xDelta  *= state.scale/oldScale;
    sprite.yDelta  *= state.scale/oldScale;
  });
  state.missiles.forEach(function (sprite) {
    sprite.xCentre *= state.scale/oldScale;
    sprite.yCentre *= state.scale/oldScale;
    sprite.xDelta  *= state.scale/oldScale;
    sprite.yDelta  *= state.scale/oldScale;
  });
}

function initState() {
  state.sprites[0] = createSpaceship();
  for (let idx = 1; idx <= 13; idx++) {
    state.sprites[idx] = createAsteroid();
  }
}

4. animationLoop()

/**
 * The thing that freezes Jasmine to make this untestable
 * @function animationLoop
 * @returns {undefined} Never returning infinite loop
 */
function animationLoop() {
  clearScene();  // in chess_image
  drawState();
  playSound();
  updateState();
  window.requestAnimationFrame(animationLoop);
}

Constants

Project Home Page

Last updated on 6 Jan 2021
Published on 6 Jan 2021

Content Footer