0

I am creating a guessing game for teams athletes have played on sequentially. But when a user types in the correct answer, remainingAttempts are being subtracted as if they got the answer incorrect. Attempts should only be subtracted per guess if it does not match whats in the first value of the array index.

const data = [
  { "fName": "Alex", "lName": "Len", "position": "C", "teamSequence": ["Phoenix Suns", "Atlanta Hawks", "Sacramento Kings", "Toronto Raptors", "Washington Wizards", "Sacramento Kings"] },
  { "fName": "KZ", "lName": "Okpala", "position": "F", "teamSequence": ["Miami Heat", "Sacramento Kings"] },
  { "fName": "Matthew", "lName": "Dellavedova", "position": "G", "teamSequence": ["Cleveland Cavaliers", "Milwaukee Bucks", "Cleveland Cavaliers", "Sacramento Kings"] },
  { "fName": "Chima", "lName": "Moneke", "position": "F", "teamSequence": ["Sacramento Kings"] }
];

//Choose a random player from the data set for the user to guess
var player;
// var teamSequence;
var teams;

$(document).ready(function getRandomPlayer() {
  // Create array of object keys
  const keys = Object.keys(data)

  // Generate random index based on number of keys
  const randIndex = Math.floor(Math.random() * keys.length)

  // Select a key from the array of keys using the random index
  const randKey = keys[randIndex]

  // Use the key to get the corresponding name from the "names" object
  player = data[randKey]
  $('#mainDiv').text((player.fName + " " + player.lName));

  // get team sequence & count
  teamSequence = player.teamSequence;
  console.log('teamSequence: ' + teamSequence);

  teams = teamSequence.length;

});

var remainingAttempts = 5;
var correct = 0;
var form = document.getElementById("form");

// submit form when enter button is pressed
function readInput(el, e) {
  if (e.keyCode == 13) {
    for (var i = 0; i < teams; i++) {
      // player.teamSequence[i]
      let inputVal = document.getElementById('inputField').value;
      if (inputVal === teamSequence[0]) {
        correct++;
        $('#correctAnswers').text(correct + ' correct so far');
        $('#attempts').hide();
        teamSequence.shift();
        console.log(teamSequence);
        form.reset();
        break
      } else {
        remainingAttempts--;
        $('#attempts').text('Remaining Attempts: ' + remainingAttempts);
        $('#attempts').show();
        form.reset();
      }
    }
    if (teamSequence.length === 0) {
      $("input").prop('disabled', true);
      // $('#answerReveal').text(teamSequence + ' is correct!');
    } else if (remainingAttempts == 0) {
      $('#mainDiv').text('Out of tries');
      $('#inputField, #attempts, .modal-title, #numOfGuesses').hide();
      $('#answerReveal').text('Sorry, you missed ' + teamSequence);
      // $("input").prop('disabled', true);
    }
  }
}
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<div class="d-flex w-75 h-100 p-3 mx-auto flex-column">
  <header class="mb-auto">
    <div>
      <nav class="nav nav-masthead justify-content-center float-md-end">
      </nav>
    </div>
  </header>
  <div class="row">
    <div class="col-12">
      <h1 id="mainDiv"></h1>
      <form id="form" autocomplete="off" action="/action_page.php">
        <div class="form-group autocomplete d-inline-flex align-items-center mt-3 w-50">
          <input type="text" class="form-control" id="inputField" onkeydown="readInput(this, event)" required>
        </div>
      </form>
      <h5 class="mt-3" id="attempts"></h5>
      <h5 class="mt-3" id="correctAnswers"></h5>
    </div>
  </div>
</div>
  • You should only add the content of the `` tag in the HTML section of the snippet editor: [I've been told to create a "runnable" example with "Stack Snippets". How do I do that?](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) – Andreas Sep 14 '22 at 16:08
  • I don't understand the logic in your loop. If the input matches the first element of `teamSequence` you remove the first element with `teamSequence.shift()`. Then you test if the input does *not* equal the first element, which was the previous second element. I suspect you just wanted to use `else:`. You should also break out of the loop when you find a match. – Barmar Sep 14 '22 at 16:11
  • You should use `e.preventDefault()` to keep the Return key from submitting the form. – Barmar Sep 14 '22 at 16:12
  • @Barmar I updated the code to include the else and break out of the loop after finding a match. However, I would like to include the functionality of the return key submitting the form. – bikeyredcycle2190 Sep 14 '22 at 16:17
  • The code clears the input field, and so the form can't be submitted because the field is required. – Barmar Sep 14 '22 at 16:23
  • @Barmar, technically the form never has to be submitted, I'm just checking if the input field matches what it needs to from the array, clearing it, and repeating until the array is empty – bikeyredcycle2190 Sep 14 '22 at 16:25

1 Answers1

1

You don't need the for loop. You only care if they entered the first element of the team sequence. If they did, it's correct, otherwise you reduce the number of remaining attempts.

const data = [{
    "fName": "Alex",
    "lName": "Len",
    "position": "C",
    "teamSequence": ["Phoenix Suns", "Atlanta Hawks", "Sacramento Kings", "Toronto Raptors", "Washington Wizards", "Sacramento Kings"]
  },
  {
    "fName": "KZ",
    "lName": "Okpala",
    "position": "F",
    "teamSequence": ["Miami Heat", "Sacramento Kings"]
  },
  {
    "fName": "Matthew",
    "lName": "Dellavedova",
    "position": "G",
    "teamSequence": ["Cleveland Cavaliers", "Milwaukee Bucks", "Cleveland Cavaliers", "Sacramento Kings"]
  },
  {
    "fName": "Chima",
    "lName": "Moneke",
    "position": "F",
    "teamSequence": ["Sacramento Kings"]
  }
];

//Choose a random player from the data set for the user to guess
var player;
// var teamSequence;
var teams;

$(document).ready(function getRandomPlayer() {
  // Create array of object keys
  const keys = Object.keys(data)

  // Generate random index based on number of keys
  const randIndex = Math.floor(Math.random() * keys.length)

  // Select a key from the array of keys using the random index
  const randKey = keys[randIndex]

  // Use the key to get the corresponding name from the "names" object
  player = data[randKey]
  $('#mainDiv').text((player.fName + " " + player.lName));

  // get team sequence & count
  teamSequence = player.teamSequence;
  console.log('teamSequence: ' + teamSequence);

  teams = teamSequence.length;

});

var remainingAttempts = 5;
var correct = 0;
var form = document.getElementById("form");

// submit form when enter button is pressed
function readInput(el, e) {
  if (e.keyCode == 13) {
    // player.teamSequence[i]
    let inputVal = document.getElementById('inputField').value;
    if (inputVal === teamSequence[0]) {
      correct++;
      $('#correctAnswers').text(correct + ' correct so far');
      $('#attempts').hide();
      teamSequence.shift();
      console.log(teamSequence);
      form.reset();
    } else {
      remainingAttempts--;
      $('#attempts').text('Remaining Attempts: ' + remainingAttempts);
      $('#attempts').show();
      form.reset();
    }
    if (teamSequence.length === 0) {
      $("input").prop('disabled', true);
      // $('#answerReveal').text(teamSequence + ' is correct!');
    } else if (remainingAttempts == 0) {
      $('#mainDiv').text('Out of tries');
      $('#inputField, #attempts, .modal-title, #numOfGuesses').hide();
      $('#answerReveal').text('Sorry, you missed ' + teamSequence);
      // $("input").prop('disabled', true);
    }
  }
}
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<div class="d-flex w-75 h-100 p-3 mx-auto flex-column">
  <header class="mb-auto">
    <div>
      <nav class="nav nav-masthead justify-content-center float-md-end">
      </nav>
    </div>
  </header>
  <div class="row">
    <div class="col-12">
      <h1 id="mainDiv"></h1>
      <form id="form" autocomplete="off" action="/action_page.php">
        <div class="form-group autocomplete d-inline-flex align-items-center mt-3 w-50">
          <input type="text" class="form-control" id="inputField" onkeydown="readInput(this, event)" required>
        </div>
      </form>
      <h5 class="mt-3" id="attempts"></h5>
      <h5 class="mt-3" id="correctAnswers"></h5>
    </div>
  </div>
</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • is there a way to check in the if statement `if (inputVal === teamSequence[0])` without regarding case? This way if a user types in all lowercase or all uppercase it would still be correct. – bikeyredcycle2190 Sep 14 '22 at 16:57
  • `if (inputVal.toLowerCase() == teamSequence[0].toLowerCase())` – Barmar Sep 14 '22 at 16:59
  • https://stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison – Barmar Sep 14 '22 at 17:00