Как мне перезапустить мой таймер и обновить sh моей жизненной статистики без обновления окна? - PullRequest
0 голосов
/ 27 февраля 2020

Я пробую это в ванили javascript. У меня есть маленький виртуальный питомец, который случайным образом теряет характеристики жизни каждую секунду. Когда они достигают нуля, экран меняется. Моя кнопка перезапуска возвращает меня к нужному экрану, но мой таймер не запускается после нажатия кнопки перезапуска, поэтому статистика не падает go.

Я чувствую, что моя проблема связана с timePassed () и перезапуском () функционирует (до конца кода), но я сейчас запутался. Также не хочу, чтобы кнопка перезапуска обновляла окно sh, поскольку оно размещено в codepen и не разрешено.

Я действительно застрял. Вы можете помочь?

//set up levels to a start at a maximum of 4
var hunger=4;
var happiness=4;
var health=4;

//create a random number 1-3
function answer(){
return Math.floor(Math.random() * 3)+1;
     }
//time count starts at 0
var i=0;



 //every minute take away 1 randomly from x, y or z 
function decrease(){
     if (answer() === 1){
       hunger--;
     }else if (answer()===2){
       health--;
     }else if(answer()===3){
       happiness--;
     }};






//show gameplay board
function showX(){
 var x = document.getElementById("game");
     x.style.display = "block";
 }


function hideScreen() {
  var y = document.getElementById("game");
     y.style.display = "none";
}

function hideX() {
  var z = document.getElementById("dead");
     z.style.display = "none";
}
 function changeStar() {
            var star = document.getElementById('star');
            if (happiness===4) {
                star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png";
            }
            else if (happiness===3){
                star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s2.png";
            }else if (happiness===2){
              star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s3.png";
            }else if (happiness===1){
              star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s4.png";
            }
 }


 function changeDonut() {
            var donut = document.getElementById('donut');
            if (hunger===4) {
                donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png";
            }
            else if (hunger===3){
                donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h2.png";
            }else if (hunger===2){
              donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h3.png";
            }else if (hunger===1){
              donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h4.png";
            }
 }           



 function changeHeart() {
            var heart = document.getElementById('heart');
            if (health===4) {
                heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png";   
                   } else if (health===3){
                heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l2.png";
            }else if (health===2){
              heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l3.png";
            }else if (health===1){
              heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l4.png";
            }
 }      

function x(){
    document.getElementById('dead').innerHTML = '<span class="deadline">Oh, no! You killed Benny! You survived for ' + i + ' seconds. Can you do better next time?</span>';
}
  //when clicking on pill, food , game or drink, make a sou
//on dying, make a sound.
//have a restart button on the death screen

document.getElementById("food").onclick= function feed(){
  if (hunger<4){
    hunger++;
  }
}

document.getElementById("drink").onclick= function drink(){
  if (hunger<4){
    hunger++;
  }
}


document.getElementById("pill1").onclick= function heal(){
  if (health<4){
    health++;
  }
}


document.getElementById("games").onclick= function play(){
  if (happiness<4){
    happiness++;
  }
}

  var munchAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562342736/sounds/zapsplat_human_eat_biscuit_mouth_closed_28532.mp3');
     var slurpAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562342736/sounds/zapsplat_human_drink_from_glass_slurp_single_21665.mp3');
var laughAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562343433/sounds/zapsplat_human_male_middle_aged_laugh_slightly_sinister_003_32379.mp3');
var pillAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562343433/sounds/noisecreations_SFX-NCFREE02_Synth-Swell.mp3');


     function myAudioFunction(verb) {
         if(verb === 'munch') {
             munchAudio.play();
         } else if(verb === 'slurp') {
             slurpAudio.play();
         } else if(verb === 'laugh'){
           laughAudio.play();
         }else if(verb === 'pill'){
           pillAudio.play();
         }
     }
//function that uses random number to decrease vital stats and change images as the stats go down
  function timePassed(){
     i++;
     answer();
     decrease();
     changeStar();
  changeDonut();
  changeHeart();
    // once stats hit 0, stop timer and hide Benny to show death message
     if (hunger==0|| happiness==0|| health==0){
   clearInterval(timer);
      x();
       hideScreen();

  }
  }
    var timer= setInterval('timePassed()', 1000);

//restart function
function restart(){
    health=4;
  happiness=4;
  hunger=4;
  showX();
  hideX();
   timePassed();
  }

var button = document.getElementById("restart");

button.onclick = function() {
   restart();
 };

1 Ответ

0 голосов
/ 28 февраля 2020

Не могли бы вы попробовать завершить функцию сброса повторным вызовом переменной timer?

Я подозреваю, что setInterval прерывается, когда вызывается функция перезапуска, и функция времени проходит, таким образом, вызывается снова.

...