Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

Rock-Paper-Scissors game in JavaScript. Infinite loop issue

$
0
0

I am learning JavaScript through The Odin Project and currently stucked with the Rock-Paper-Scissors exercise. Program below works properly at a single round but when I add a for loop to the game() function to call playRound() for five times and keep score it gives an infinite loop error for the line where for loop is.

The program could be configured differently but this is what the project requests. Any help is appreciated.


//random choice generator
  function computerPlay() {

    function getRandomArbitrary(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    let number = getRandomArbitrary(0, 3)
    if (number == 0) {
      return 'ROCK'
    } else if (number == 1) {
      return 'PAPER'
    } else {
      return 'SCISSORS'
    }
  }


  /////////////////////////////////////////////////////////////////////////////////////////////

// Single Round Main

  function playRound(playerSelection, computerSelection) {


    playerSelection = playerSelection.toUpperCase()


    if (computerSelection == playerSelection) {
      console.log('DEUCE')
      return 0
    } else if ((playerSelection == 'ROCK'&& computerSelection == 'SCISSORS') || (playerSelection == 'PAPER'&&
        computerSelection == 'ROCK') || (playerSelection == 'SCISSORS'&& computerSelection == 'PAPER')) {
      console.log('You Win! ' + playerSelection + ' beats ' + computerSelection + '.')
      return 1
    } else if ((playerSelection == 'SCISSORS'&& computerSelection == 'ROCK') || (playerSelection == 'ROCK'&&
        computerSelection == 'PAPER') || (playerSelection == 'PAPER'&& computerSelection == 'SCISSORS')) {
      console.log('You Lose! ' + computerSelection + ' beats ' + playerSelection + '.')
      return 0
    }
  }

  /////////////////////////////////////////////////////////////////////////////////////////////

  
  function game() {

    let score = 0

    for (i = 0; i < 5; i++) {
      let computerSelection = computerPlay()
      let playerSelection = prompt('Choose one! Rock, Paper or Scissors.')
      let result = playRound(playerSelection, computerSelection)


      if (result == 1) {
        score += 1
      } else {
        score += 0
      }
    }
    console.log(score)
  }


  game()

Viewing all articles
Browse latest Browse all 138221

Trending Articles