显示消息和计时器:不起作用

时间:2018-01-31 02:55:06

标签: javascript jquery arrays timer

这是Memory游戏的Javascript代码。

我已经为这个项目尝试了不同的时间代码,包括我从堆栈溢出中获得的代码,但没有一个正在运行。

计时器永远不会显示。我正在尝试制作计时器

  • 游戏开始时
  • 比赛期间
  • 比赛结束后

我想在获胜者获胜时显示的短消息或提示不起作用。

当用户获胜时,没有真正显示的内容。

只有重置按钮才会重置游戏。

在这些情况下让计时器显示的最佳方法是什么?



/*
 * Create a list that holds all of your cards
 */
const cardSymbols = ['fa-diamond', 'fa-diamond', 'fa-paper-plane-o', 'fa-paper-plane-o', 'fa-anchor', 'fa-anchor', 'fa-bolt', 'fa-bolt',
                    'fa-cube', 'fa-cube', 'fa-leaf', 'fa-leaf', 'fa-bicycle', 'fa-bicycle', 'fa-bomb', 'fa-bomb'];

let shakeDeck = shuffle(cardSymbols);

/*
 * Display the cards on the page
 */

// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
    let currentIndex = array.length, temporaryValue, randomIndex;

    while (currentIndex !== 0) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}


function makeDeck() {
  $(".deck").empty()
  shakeDeck.forEach(function(card, index){
    const cardElement = '<li class="card"><i class="fa ' + card + '"></i></li>'
    $(".deck").append(cardElement);
  })
}

makeDeck();

var clicks = 0;

function lessStars(clicks) {
    var starRating = [5,10];
    var stars = starRating.length;
    $('.stars').children().each(function(i, starElem) {
    if (starRating[i] === clicks) $(starElem).addClass("star-lost")
  });
}

function forStar() {
  var val = $(".stars").html();
 return val;
}

function countMoves(clicks) {
  $('.moves').text(clicks);
}

function openModal() {
  $("#time-needed").text(timeNeeded);
  console.log(timeNeeded);
  $("#moves-needed").text(clicks);
  $("#score-panel").html(forStar());
  $("#myModal").modal("show")
}

var timerOn = false;

function playGame() {
  $(".card").click(function(){
    if (!timerOn) {
      getDate();
      timerOn = true;
    }
    const $card = $(this)
    if (!$card.hasClass("open show")) {
      $card.addClass("open show");
      if (!$compare) {
        $compare = $card;
        return
      }
      clicks++
      lessStars(clicks);
      countMoves(clicks);
      if ($compare[0].innerHTML === $card[0].innerHTML) {
        console.log("match");
        $card.addClass("match");
        $compare.addClass("match");
        $compare = null;
        matchCount++;
          if (matchCount === 8){
          openModal();
          clearInterval(timer)
          alert("Woohoo!! You Won!"+"Your total time is " + elapsedTime);
          }
      } else {
        console.log("doesn't match");
        setTimeout(function(){
          $card.removeClass("open show");
          $compare.removeClass("open show");
          $compare = null;
        },300)
    }
    } else {
      $card.attr('disabled', true);
    }
  });
}

playGame();

let $compare = null
let matchCount = 0
var timer;
let timeNeeded = "";
var allSeconds = 0;

// timer https://stackoverflow.com/questions/2604450/how-to-create-a-jquery-clock-timer#answer-19744442

function getDate(){
              // var start = new Date().getTime()
               timer = setInterval(function(){
               var currentTime = new Date().getTime()
               var elapsedTime = currentTime - currentTime
               let m = Math.floor((elapsedTime % (1000 * 60 * 60)) / (1000 * 60));
               let s = Math.floor((elapsedTime % (1000 * 60)) / 1000);
               if(s < 60){
                   s = "0"+s;
               }
               timeNeeded = m + ":" + s;
               $("h3").text(m+" : "+s);
               console.log(timeNeeded);
             }, 500);
    };

//    var myVar = setInterval(myTimer, 1000);

//function myTimer() {
//    var d = new Date();
//}

function resetTimer() {
  var timerVariable = setInterval(getDate, 100);
  timeNeeded = "";
  clearInterval(getDate);
  getDate();
}

function resetGame() {
  clickCount = 0;
  timeNeeded = "";
  timer = false;
  clicks = 0;
  $('.stars').children().removeClass("star-lost")
  shuffle(cardSymbols);
  makeDeck();
  playGame();
  countMoves();
  resetTimer();
}

$('.restart').click(resetGame);



//this is the function for star ratings.
function check_stars(){
  if (moves < 11){
    stars[3].classList.add('fa-star-o');
    stars[3].classList.remove('fa-star');
  }
  else {
    stars[2].classList.add('fa-star-o');
    stars[2].classList.remove('fa-star');
  }
 /* else if(moves > 21){
    stars[1].classList.add('fa-star-o');
    stars[1].classList.remove('fa-star');
  }*/
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你可以像这样实现一个计时器:

var createTimer = () => {
  const start = Date.now();
  var done=false;
  const getMinuteSecond = now =>
    [
      Math.round((Date.now()-start)/60000), //minutes
      Math.round(((Date.now()-start)%60000)/1000) //seconds
    ];
  return {
    timePassed:()=>
      (done===false)
        ? [done,getMinuteSecond(Date.now())]
        : [true,done],
    stop:()=>
      done=getMinuteSecond(Date.now()),
    start:()=>done=false
  };
};
var updateTimePassed = timer => {
  const updateSomeHTML = html =>
    console.log("update",html);
  const intervalID = setInterval(
    _=>{
      const [done,update] = timer.timePassed();
      if(done){
        clearTimeout(intervalID);
      }
      updateSomeHTML(update);
    },
    1000
  )
};
//how to use:
var gameTimer = createTimer();
gameTimer.start();
updateTimePassed(gameTimer);
setTimeout(
  _=>gameTimer.stop(),
  3000
);

gameTimer你可以开始和停止(不暂停)updateTimePassed可以在播放时更新时间(设置html)。在您的代码中实现我的代码有一些代码太多,但您可以尝试一下,如果您需要帮助,请告诉我。

如果您需要更多帮助,请使用当前代码,您希望发生的情况,实际发生的情况以及控制台中的任何可能错误来更新您的答案。