Различные изображения на основе диапазона баллов - PullRequest
0 голосов
/ 18 марта 2019

Недавно я читал учебник на YouTube по созданию игры типа whack-a-mole: https://www.youtube.com/watch?v=toNFfAaWghU.

Я прекрасно следовал коду до конца, и теперь мне интересно, возможно линастроить систему, которая могла бы определять счет пользователя, когда время истекает, и показывать разные картинки (1-5 звездных оценок) на основе диапазона оценок.

Вот код:

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Whack-A-Bear!</title>
  <link href='https://fonts.googleapis.com/css?family=Amatic+SC:400,700' rel='stylesheet' type='text/css'>
  <link href='https://www.cssfontstack.com/Gill-Sans' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="style.css">
</head>
<body>

<audio autoplay>
  <source src="Outrun - Original Arcade Music.mp3" type="audio/mpeg">
</audio>

  <h1>Whack-A-Bear! <span class="score">0</span></h1>
    <center><h2>But Not A Hare!!</h2></center>

  <div id="timer">
  <h2>Timer</h2>
  <p id="TimerDisplay">00:15</p>
  </div>

  <center><button onClick="startGame()">Click Here To Start!</button></center>
  <div class="game">

  <div class="hole hole1">
      <div class="mole"></div>
    </div>
    <div class="hole hole2">
      <div class="mole"></div>
    </div>
    <div class="hole hole3">
      <div class="mole"></div>
    </div>
    <div class="hole hole4">
      <div class="mole"></div>
    </div>
    <div class="hole hole5">
      <div class="mole"></div>
    </div>
    <div class="hole hole6">
      <div class="mole"></div>
    </div>  
  </div>

<script>

/*https://medium.freecodecamp.org/javascripts-var-let-and-const-variables-explained-with-a-story-2038e3c6b2f9 */

  const holes = document.querySelectorAll('.hole');
  const scoreBoard = document.querySelector('.score');
  const moles = document.querySelectorAll('.mole');

  /*The querySelector() method only returns the first element that matches the specified CSS selectors. 
  To return all the matches, use the querySelectorAll() method instead.*/

  let lastHole;
  let timeUp = false;
  let score = 0;

  //set random timing for the moles to pop up
  function randomTime(min, max) {
    return Math.round(Math.random() * (max - min) + min);
  }

//set random holes for the moles to pop up from the list of our six holes
  function randomHole(holes) {
    const idx = Math.floor(Math.random() * holes.length);
    const hole = holes[idx];
    // if by chance, we keep getting the same one as the last one, run the function again 
    if (hole === lastHole) {
    //shows that it was about to show you the same hole but didn't so ran the function again
      console.log('Ah nah thats the same one bud');
      return randomHole(holes);
    }
    lastHole = hole;
    return hole;
  }
  function peep() {
  var imgs = ["yes.png", "Final Hare.png"];
  var i = Math.floor(Math.random() * imgs.length);
  var raccoon = document.getElementById('raccoon.png');

  // these random times refer to how long the mole will stay popped up
    const time = randomTime(200, 1000);
    const hole = randomHole(holes);
    //shows the random home in a random amount of time
    console.log(time, hole);
    var mole = hole.querySelector(".mole");
  mole.style.background = "url('" + imgs[i] + "') bottom center no-repeat";
  mole.style.backgroundSize = "60%";
    //triggers the CSS to get the mole to come up
    hole.classList.add('up');
    //makes the mole go away after it has come up => means after the time's up, remove the mole
    setTimeout(() => {
      hole.classList.remove('up');
      //if the time is not up, then run peep () again
      if (!timeUp) peep();
    }, time);
  }
  function startGame() {
    scoreBoard.textContent = 0;
    timeUp = false;
    score = 0;
    peep();
    //a Timeout function will run when time up is true at 10 seconds
    setTimeout(() => timeUp = true, 15000)


    var sec = 15;
    var timer = setInterval(function(){
    document.getElementById('TimerDisplay').innerHTML='00:'+sec;
    sec--;
    if (sec < 0) {
    clearInterval(timer);
    }

    }, 1000);



  }  
  function bonk(e) {
  //function bonk will take in an event which will be us clicking each of the moles
    //you can simulate a click in JS but here we don't want that to be possible
    if(!e.isTrusted) return; // cheater! To prevent a fake click if the event is not trusted, not clicked with mouse
    score++;
    this.parentNode.classList.remove('up');
    scoreBoard.textContent = score;
  }
  moles.forEach(mole => mole.addEventListener('click', bonk));
</script>
</body>
</html>

1 Ответ

0 голосов
/ 18 марта 2019

Используйте оператор switch для изображения на конечном экране, например

switch(true){
    case score > firstStarRatingValue:
        document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE1.png\")";
        break;
    case score > secondStarRatingValue:
        document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE2.png\")";
        break;
    case score > thirdStarRatingValue:
        document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE3.png\")";
        break;
    case score > fourthStarRatingValue:
        document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE4.png\")";
        break;
    default:
        //because you probably don't want an upper limit on score 
        document.getElementById("END IMAGE ID").style.backgroundImage = "IMAGE5.png";
}

И вы бы назвали это в конце

и так как я не знал идентификатор для конца, я просто добавил END IMAGE ID, так что это то, что вам придется изменить.

В будущем, пожалуйста, сократите ваш код до минимального примера. Это облегчает чтение тем, кто пытается помочь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...