如何在游戏开始前加载所有图像? JavaScript,预加载器

问题描述

我设计了这款游戏,这是我的第一个项目。它是 JavaScript 课程中“The Pig Game”的衍生产品。我为 UI 调整了 Pig Game 的 HTML 和 CSS 模板,但我从头开始进行游戏设计和编码。您可以在这里玩游戏:https://jeffparadox.000webhostapp.com/

我有一些问题,如果有人关心的话:

  1. 你觉得怎么样,你觉得有什么问题吗?有什么比现在更清晰的(尤其是在用户界面方面)吗?

  2. 游戏在我的组合上运行速度很快。但是当我访问该网站时,图像不会立即开始旋转;开始看到图像明显旋转大约需要 30 秒。我认为这是因为浏览器正在加载图像但代码运行速度更快。有没有办法在代码预加载这些图片,让游戏正常启动?或者,如果我清理我的代码,游戏加载速度是否会更快而无需预加载图像?

  3. 这是我的 JS 代码。如果有人有兴趣检查它并告诉我我可以清理和优化哪些部分,我将不胜感激。提前致谢:

"use strict";

// Selecting elements
const player0El = document.querySelector(".player--0");
const player1El = document.querySelector(".player--1");
const tries0El = document.getElementById("tries--0");
const tries1El = document.getElementById("tries--1");
const current0El = document.getElementById("current--0");
const current1El = document.getElementById("current--1");

const animalEl = document.querySelector(".animal");
const btnSpin = document.querySelector(".btn--spin");
const btnReset = document.querySelector(".btn--reset");
const btnRestart = document.querySelector(".btn--restart");

const youWin0El = document.querySelector("#you-win--0");
const youWin1El = document.querySelector("#you-win--1");

const highscore0El = document.querySelector(".high-score--0");
const highscore1El = document.querySelector(".high-score--1");

// Declare let variables
let triesLeft,playerscores,highscores,activePlayer,round,currentscore,playing;

// Starting conditions
const init = function () {
  youWin0El.classList.add("hidden");
  youWin1El.classList.add("hidden");
  youWin1El.textContent = "You Win! ?";
  youWin0El.textContent = "You Win! ?";
  currentscore = 0;
  triesLeft = [10,10];
  playerscores = [0,0];
  highscores = [0,0];
  activePlayer = 0;
  round = 3;
  playing = true;

  btnRestart.textContent = `? ROUND: ${round}`;

  tries0El.textContent = 10;
  tries1El.textContent = 10;
  current0El.textContent = 0;
  current1El.textContent = 0;

  animalEl.src = "noAnimal.jpg";
  player0El.classList.remove("player--winner");
  player1El.classList.remove("player--winner");
  player0El.classList.add("player--active");
  player1El.classList.remove("player--active");
};

// Initialize game
init();

// ***GAME FUNCTIONS***

// Switch players
const switchPlayer = function () {
  activePlayer = activePlayer === 0 ? 1 : 0;
  player0El.classList.toggle("player--active");
  player1El.classList.toggle("player--active");
};

// Check how many rounds left
const checkRound = function () {
  btnRestart.textContent = `? ROUND: ${round}`;
  if (round < 1) {
    gameOver();
  } else if (triesLeft[activePlayer] < 1 && round > 0) {
    if (triesLeft[0] === 0 && triesLeft[1] === 0) {
      triesLeft[0] = 10;
      triesLeft[1] = 10;
      tries0El.textContent = 10;
      tries1El.textContent = 10;
    }
    switchPlayer();
  }
};

// End of game
const gameOver = function () {
  playing = false;
  if (playerscores[0] > playerscores[1]) {
    youWin0El.classList.remove("hidden");
  } else if (playerscores[0] < playerscores[1]) {
    youWin1El.classList.remove("hidden");
  } else if (playerscores[0] === playerscores[1]) {
    youWin1El.textContent = "It's a Tie ?";
    youWin0El.textContent = "It's a Tie ?";
    youWin1El.classList.remove("hidden");
    youWin0El.classList.remove("hidden");
  }
};

// Check the rabbit,increase and log the score
const checkRabbit = function () {
  if (imageNumber === 0) {
    currentscore =
      Number(document.getElementById(`current--${activePlayer}`).textContent) +
      1;
    playerscores[activePlayer] = currentscore;
    document.getElementById(
      `current--${activePlayer}`
    ).textContent = currentscore;
  }
};

// Update tries left
const triesUpdate = function () {
  triesLeft[activePlayer] -= 1;
  document.getElementById(`tries--${activePlayer}`).textContent =
    triesLeft[activePlayer];
};

// Update high scores
const registerHighscore = function () {
  if (playerscores[activePlayer] > highscores[activePlayer]) {
    highscores[activePlayer] = playerscores[activePlayer];
    document.getElementById(
      `high-score--${activePlayer}`
    ).textContent = `High score: ${highscores[activePlayer]}`;
  }
};

// ***GAME ENGINE***

// Declare game engine variables
let interval,imageNumber;

// Spinning images
btnSpin.addEventListener("click",function () {
  if (playing) {
    // Change button to Stop
    btnSpin.textContent = `⛔ STOP!`;
    // Stop the spinning (Runs only when interval is declared)
    if (interval) {
      clearInterval(interval);
      interval = null;
      btnSpin.textContent = `? SPIN!`;
      triesUpdate();
      checkRabbit();
      registerHighscore();
      if (triesLeft[0] < 1 && triesLeft[1] < 1) {
        round -= 1;
      }
      checkRound();
      // Start the spinning (Runs only when interval is null or undefined)
    } else {
      // Loop with time intervals
      interval = setInterval(function () {
        // Genarate image number
        imageNumber = Math.trunc(Math.random() * 10);
        // Show image with the generated number
        animalEl.src = `animal-${imageNumber}.jpg`;
      },5);
    }
  }
});

// ***RESET GAME***
btnReset.addEventListener("click",init);

解决方法

您可以通过将其放入您使用的每个图像的 <head> 中来预加载图像:

<link rel="preload" as="image" href="animal-1.png">

此处有更多文档:https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

至于其他问题,它们可能更适合 SE Code Review:https://codereview.stackexchange.com/