Переменная отслеживания попыток пользователя не обновляется - PullRequest
0 голосов
/ 25 ноября 2018

Я работаю над игрой-викториной, и у меня уже давно есть эта проблема, и я просто не могу понять, что я делаю неправильно.Задайте любой вопрос, если вас смущают мои объяснения, я буду следить за этим сообщением

Как воссоздать проблему - введите имя, отображаемое на экране, пока не появится надпись "Игра окончена, братан!"- Проблема: когда я набираю имя в поле ввода и нажимаю «Ответить», чтобы проверить, совпадает ли значение поля ввода с именем, полученным из API, возникает переменная (var попытки = 5), отслеживающая, сколько раз пользователь имелпопытался задать вопрос, но эта переменная (пытается) уменьшает свое значение на единицу при правильном ответе, она должна делать это только при неправильном ответе.

Также, дайте мне знать, что вы думаете о коде JSэто плохой код?Я спрашиваю, потому что код в функции newReq, который я написал дважды, загружает и отображает данные, полученные из API при загрузке страницы, код внутри функции newReq загружает новый символ при нажатии кнопки «Новый символ». Я былвсе время думал о СУХОЙ, но я не уверен, как загрузить нового персонажа без переписывания кода

var attemptsPara = document.querySelector("#attempts"),
  attempts = 5,
  scorePara = document.querySelector("#score"),
  score = 0,
  feedBackDiv = document.querySelector("#feedBack"),
  newCharacterBtn = document.querySelector("#newCharacter"),
  answerBtn = document.querySelector("#answer"),
  input = document.querySelector("input");

scorePara.textContent = `Score is currently: ${score}`;
attemptsPara.textContent = `${attempts} attempts remaining`;

var feedBackText = document.createElement("p");

var characterPara = document.querySelector("#character");

//click new character button to load new character
// newCharacterBtn.addEventListener("click", () => {
//   answerBtn.disabled = false;
//   attempts = 5;
//   attemptsPara.textContent = `${attempts} attempts remaining`;
// });

//function that displays retrieved data to the DOM
function displayCharacters(info) {
  let englishName = info.attributes.name;
  characterPara.textContent = `This is the character's name: ${englishName}`;
  console.log(englishName, randomNumber);
}


//load new character
var randomNumber = Math.round(Math.random() * 100 + 2);
var request = new XMLHttpRequest();
request.open(
  "GET",
  "https://kitsu.io/api/edge/characters/" + randomNumber,
  true
);

request.send();

request.onload = function() {
  var data = JSON.parse(this.response);
  var info = data.data;
  displayCharacters(info);

  //checks if the input value matches name retrieved
  answerBtn.addEventListener("click", () => {
    let englishName = info.attributes.name;
    if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      setTimeout(() => {
        feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq(); //call function to load and display new character
    } else {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      setTimeout(() => {
        feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
        answerBtn.disabled = true;
        attemptsPara.textContent = `Game over bro!`;
      }
    }
    console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
  });
};

newCharacterBtn.addEventListener("click", newReq);

//function to make a new request and display it the information on the DOM,when New character button is clicked
function newReq() {
  rand = randomNumber = Math.round(Math.random() * 100 + 2);
  var request = new XMLHttpRequest();
  request.open(
    "GET",
    "https://kitsu.io/api/edge/characters/" + randomNumber,
    true
  );

  request.send();

  request.onload = function() {
    var data = JSON.parse(this.response);
    var info = data.data;
    displayCharacters(info);

    answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
        feedBackText.textContent = `${input.value} is correct`;
        feedBackDiv.append(feedBackText);
        feedBackDiv.style.backgroundColor = "green";
        feedBackDiv.style.display = "block";
        //settimeout to hide feedBack div
        setTimeout(() => {
          feedBackDiv.style.display = "none";
        }, 3000);
        score = score + 5;
        scorePara.textContent = `Score is currently: ${score}`;
        attempts = 5;
        attemptsPara.textContent = `${attempts} attempts remaining`;
        input.value = "";
        newReq();
      } else if (input.value != englishName) {
        feedBackText.textContent = `${input.value} is wrong`;
        feedBackDiv.append(feedBackText);
        feedBackDiv.style.backgroundColor = "red";
        feedBackDiv.style.display = "block";
        input.focus();
        //settimeout to hide feedBack div
        setTimeout(() => {
          feedBackDiv.style.display = "none";
        }, 2000);
        attempts = attempts - 1;
        attemptsPara.textContent = `${attempts} attempts remaining`;

        if (attempts <= 0) {
          answerBtn.disabled = true;
          attemptsPara.textContent = `Game over bro!`;
        }
      }
    });
    console.log(attempts);
  };
}
body {
  margin: 0;
  padding: 0;
  background: black;
}

#imageHolder {
  height: 560px;
  width: 1100px;
  background: #098;
  margin: 10px auto;
}

#buttonHolder {
  /* background: #453; */
  width: 160px;
  margin: 0 auto;
}

p,
h3 {
  color: yellowgreen;
  text-align: center;
}

h3 {
  text-decoration: underline;
}

img {
  width: 100%;
  height: 100%;
}

button,
input {
  margin: 10px 10px;
  border: none;
  background: #098;
  display: block;
}

input {
  background: white;
}


/* for the question and awnswer game */

#feedBack {
  background: #098;
  height: 120px;
  width: 320px;
  margin: 10px auto;
  display: none;
}
<p id="score"></p>

<p id="character"></p>

<input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

<p id="attempts"></p>

<div id="feedBack">

</div>

1 Ответ

0 голосов
/ 25 ноября 2018

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

Добавьте консольный журнал в начале события click, и вы увидите, что после 2-го ответа событие щелчка происходит дважды, затем трижды при 3-м ответе и т. Д. '.Это означает, что при первом щелчке результат верный, но затем при остальных щелчках он неверный и должен вызывать ошибку.

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

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