Sam Akers
Sam Akers

Reputation: 39

Rock Paper Scissors JS Game

I'm a complete beginner with JS and I'm struggling to understand the logic with this one. Nothing is being logged in the console, although I am getting the alert inputs. Can anyone point out where I'm going wrong? Is it perhaps something to do with scope? I feel like this should be really simple but I can't get it working.

function computerPlay() {
    const options = ['rock', 'paper', 'scissors'];
    let result = options[Math.floor(Math.random() * options.length)];
    return result;
}

function playRound(playerSelection, computerSelection) {
    let selection = prompt('Please enter your selection');
    let playerScore = 0;
    let computerScore = 0;
    let result = "";

    computerSelection = computerPlay();

    playerSelection = selection.toLowerCase();
    if (playerSelection == 'rock') {
        if (computerSelection == 'rock') {
            return ["It's a draw!", playerScore + 1, computerScore + 1];
        } else if (computerSelection == 'paper') {
            return ["You lose!", computerScore + 1];
        } else {
            return ["You win!", computerScore + 1];
        }
    } else if (playerSelection == 'paper') {
        if (computerSelection == 'paper') {
            return "It's a draw!";
        } else if (computerSelection == 'scissors') {
            return "Computer wins!";
        } else {
            return "You win!";
        }
    } else if (playerSelection == 'scissors') {
        if (computerSelection == 'scissors') {
            return "It's a draw!"
        } else if (computerSelection == 'rock') {
            return "Computer wins!"
        } else {
            return "You win!"
        }
    }

    return result + "Player Score = " + playerScore + "Computer Score = " + computerScore;

}

function game() {

    for (let i = 0; i < 5; i++) {
        computerPlay();
        playRound();
    }

}

console.log(game())

Upvotes: 0

Views: 75

Answers (2)

James Oshomah
James Oshomah

Reputation: 224

Modify the game function this way.

function game() {

  for (let i = 0; i < 5; i++) {
      const result = playRound();
      console.log(result)
  }

}
game()

Then you call game(). You will be able to see your console log and also you do not need to call the computerPlay function inside the game function. It's functionality is already called in the playRound function. Hope this helps cheers

Upvotes: 0

jacob13smith
jacob13smith

Reputation: 929

Move your console log from where it is to inside the game() function like so:

for (let i = 0; i < 5; i++) {
    console.log(playRound());
}

You also don't need to call computerPlay() in the game function, as it is doing nothing.

Upvotes: 1

Related Questions