Многопользовательские каменные ножницы в огненной базе, обзорная проблема - PullRequest
0 голосов
/ 05 февраля 2019

Я работаю над игрой «Ножницы из каменной бумаги», которая позволяет двум игрокам противостоять друг другу.Здесь и там я получаю сообщение об ошибке, что TypeError: Cannot read property 'p1throw' of null Кажется, что слушатели firebase работают, и в некоторых случаях переменная результатов не полностью удаляется, а некоторые разделы кода выполняются несколько раз.

Я пробовал тонну консольных журналов, чтобы изолировать проблему, но иногда код работает просто отлично, а затем он выдает ошибку в других случаях.

//
// GAME MECHANICS
//


// Function to increase move count
function progressMove(num) {
  database
    .ref("/moves")
    .child("/move")
    .set(num);
}

//Listener for when move variable changes
database.ref("/moves").on("value", function(snap) {
  console.log("Move just changed to " + snap.val().move);
  if (snap.val().move === 1) {
    playerOneThrow(snap.val().move);
  }
  if (snap.val().move === 2) {
    playerTwoThrow(snap.val().move);
  }
  if (snap.val().move === 3) {
      console.log("Move is 3, evaluating match")
    evaluateMatch();
    database.ref("/results/gameresult").remove()
    console.log("removed the results node")
  }
});

function playerOneThrow() {
  $(".details").text("Player 1, choose your throw");
  $(".p1-hands").on("click", playerOneChooseHand);
}

function playerOneChooseHand() {
  $(".p1-hands").off()
  let hand = $(this).attr("data-value");
  console.log("Player 1 chose" + hand);
  progressMove(2);
  database.ref("/throws/p1throw").child("/throwVal").set(hand);
}

function playerTwoThrow() {
  $(".details").text("Player 1 has thrown, player 2, choose your throw");
  $(".p2-hands").on("click", playerTwoChooseHand);
}

function playerTwoChooseHand() {
  $(".p2-hands").off()
  progressMove(3);
  console.log("Player 2 hand clicked");
  let hand = $(this).attr("data-value");
  console.log("Player 2 chose" + hand);
  database.ref("/throws/p2throw").child("/throwVal").set(hand);
}

function evaluateMatch() {
    database.ref("/throws/")
    .once("value")
    .then(function(throwsnap) {
        console.log("Displaying throws node once for match evaluation")
        console.log(throwsnap.val())
            let p1throw = throwsnap.val().p1throw.throwVal;
            let p2throw = throwsnap.val().p2throw.throwVal;
            if (p1throw === p2throw){
                database.ref('/results/gameresult').child("/outcome").set("tie")
            } else if(p1throw === "rock"){
                if(p2throw === "paper"){
                database.ref('/results/gameresult').child("/outcome").set("p2 wins")
                } else if(p2throw === "scissors")
                database.ref('/results/gameresult').child("/outcome").set("p1 wins")
            } else if (p1throw === "paper"){
                if(p2throw === "rock"){
                database.ref('/results/gameresult').child("/outcome").set("p1 wins")
                } else if (p2throw === "scissors"){
                database.ref('/results/gameresult').child("/outcome").set("p2 wins")
                }
            } else if(p1throw === "scissors"){
                if(p2throw === "paper"){
                database.ref('/results/gameresult').child("/outcome").set("p1 wins")
                } else if (p2throw === "rock"){
                 database.ref('/results/gameresult').child("/outcome").set("p2 wins")
                }
            }
        });
    }

// Listens for change in results, triggered by setting outcome and results above
database.ref('/results/gameresult').on("child_added",function(resultsnap){
    console.log("Displaying results node because a child was added", resultsnap.val())
    database.ref("/throws/").once("value").then(function(throwsnap) {
          console.log("Displaying the throws node just once since a child was added to the game results node")
        console.log(throwsnap.val()) 
          if(resultsnap.val() === "tie"){
              ties++
          } else if (resultsnap.val() === "p1 wins"){
              p1wins++
              p2losses++
          } else if(resultsnap.val() === "p2 wins"){
              p2wins++
              p1losses++
          }
          database.ref("/moves").child("/move").set(1); //Bring game back to p1throw point
          $(".details").prepend("The result was: " + resultsnap.val() + "<br><br>");
          $(".details").prepend(" Player 1 chose " + throwsnap.val().p1throw.throwVal + " and player 2 chose " + throwsnap.val().p2throw.throwVal + "<br><br>");
          database.ref("/throws").remove()
          console.log(ties + " ties")
          console.log(p1wins + " p1wins")
          console.log(p2wins + " p2wins") 
          // Update results on page 
          database.ref('/results/gameresult').on("value",function(snap){
            console.log("Updating screen for both because game result has changed")
            $("#p1-wins").text(p1wins)
            $("#p2-wins").text(p2wins)
            $("#p1-losses").text(p1losses)
            $("#p2-losses").text(p2losses)
            $(".ties").text(ties)
        });
    });
});

Я ожидал, что вывод в div #details будет корректно обновляться, и я, честно говоря, просто не уверен, почему эта ошибка появляется только время от времени, и нет четкой картины?

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