Rock Paper Scissors assigning points each round

730 Views Asked by At

newbie here! Just starting learning week and a half ago. Creating the rock paper scissors game. The goal is to play 5 rounds against the computer to determine the overall winner. I'm a little stumped when it comes to how I can award the player a point if they win or the computer a point if it wins. Also all critiques of code are welcome as well.

Thanks a ton!

code so far...

let array = ['rock', 'paper', 'scissor'];

const getComputerChoice = () => {
  let random = Math.floor((Math.random() * 3));
  let randomNames = array[random];
  return randomNames;
}

const game = () => {
 
  for (let i = 0; i < 5; i++) {
    let input = prompt('Choose rock, paper or scissor');
    const playerSelection = input.toLowerCase();
    const computerChoice = getComputerChoice();
    
    const computerWins = `Computer Wins! ${computerChoice} beats ${playerSelection}.`;
    const playerWins = `Player wins! ${playerSelection} beats ${computerChoice}.`;
    const tie = `It's a tie, ${playerSelection} is equal to ${computerChoice}.`;

    if (playerSelection !== 'rock' && playerSelection !== 'paper' && playerSelection !== 'scissor') {
      i = i - 1;
      console.log("Nice try! Please enter a valid input.");
    }
    if (playerSelection === 'rock' && computerChoice === 'paper' || playerSelection === 'paper' && computerChoice === 'scissor' || playerSelection === 'scissor' && computerChoice === 'rock') {
        console.log(computerWins);
    } 
    if (playerSelection === 'paper' && computerChoice === 'rock' || playerSelection === 'scissor' && computerChoice === 'paper' || playerSelection === 'rock' && computerChoice === 'scissor') {
        console.log(playerWins);
    } else {
        if (playerSelection === computerChoice) {
          console.log(tie);
          }
      }
  }
}

game();
4

There are 4 best solutions below

0
Shozab javeed On

just add variable of score and increment after each win

let array = ['rock', 'paper', 'scissor'];
    let player_score=0;
    let computer_score=0;
    const getComputerChoice = () => {
      let random = Math.floor((Math.random() * 3));
      let randomNames = array[random];
      return randomNames;
    }
    
    const game = () => {
     
      for (let i = 0; i < 5; i++) {
        let input = prompt('Choose rock, paper or scissor');
        const playerSelection = input.toLowerCase();
        const computerChoice = getComputerChoice();
        
        const computerWins = `Computer Wins! ${computerChoice} beats ${playerSelection}.`;
        const playerWins = `Player wins! ${playerSelection} beats ${computerChoice}.`;
        const tie = `It's a tie, ${playerSelection} is equal to ${computerChoice}.`;
    
        if (playerSelection !== 'rock' && playerSelection !== 'paper' && playerSelection !== 'scissor') {
          i = i - 1;
          console.log("Nice try! Please enter a valid input.");
        }
        if (playerSelection === 'rock' && computerChoice === 'paper' || playerSelection === 'paper' && computerChoice === 'scissor' || playerSelection === 'scissor' && computerChoice === 'rock') {
                computer_score+=1;
            console.log(computerWins);
        } 
        if (playerSelection === 'paper' && computerChoice === 'rock' || playerSelection === 'scissor' && computerChoice === 'paper' || playerSelection === 'rock' && computerChoice === 'scissor') {
            player_score+=1;
            console.log(playerWins);
        } else {
            if (playerSelection === computerChoice) {
              console.log(tie);
              }
          }
      }
      console.log("Computer:"+computer_score+' vs '+'Player:'+player_score);
    }
    
    game();
3
Dario Pisapia On

You can add 2 variables like.

  let playerPoints = 0;
  let computerPoints = 0;

then, where you console.log the winner of a round you can add 1 at their counter.

    if (playerSelection === 'rock' && computerChoice === 'paper' || playerSelection === 'paper' && computerChoice === 'scissor' || playerSelection === 'scissor' && computerChoice === 'rock') {
    computerPoints += 1
    console.log(computerWins);
} 
    if (playerSelection === 'paper' && computerChoice === 'rock' || playerSelection === 'scissor' && computerChoice === 'paper' || playerSelection === 'rock' && computerChoice === 'scissor') {
    playerPoints += 1
    console.log(playerWins)

Then you have the points. With them you can add another if to control if someone has won (when reach 3 points for example).

0
John Ingram On

Like Wiktor said in his comment, you can store the victories in variables, that you increment every time someone wins.

Before your for loop, you you'd initialize two variables, one for Computer wins, and one for Human wins:

var compWins = 0;
var humanWins = 0;

Then, when someone wins, you would increment the appropriate variable:

compWins++;

or

humanWins++;

0
zer00ne On

Do not use prompt(), confirm(), or alert(), they are horrible for UX. You need to use HTML if you are interacting with the user preferably <form> and form controls which are designed specifically for user interaction.

Details are commented in example

// Define the scores outside of event handler
let w = 0,
  l = 0,
  d = 0,
  turns = 5;
// Reference the <form>
const rps = document.forms.rps;

// Event handler passes event object by default
const game = (e) => {
  // Reference the tag user clicked
  const clicked = e.target;
  // If the user clicked a <button>...
  if (clicked.matches('button')) {
    // Decrement turn counter
    turns--;
    // Get a random number in the range of 0 to 2
    const opponent = 3 * Math.random() << 0;
    // Get the value of the <button> user clicked (will be 0 to 2)
    const player = +clicked.value;

    /*
     Index number of the array is determined by the number of the player
     and opponent
     */
    const icon = ['', '', '✂️'];
    const playerIcon = icon[player];
    const opponentIcon = icon[opponent];

    // Message is determined by outcome
    const L = `Opponent wins! ${opponentIcon} beats ${playerIcon}.`;
    const W = `You win! ${playerIcon} beats ${opponentIcon}.`;
    const D = `It's a tie, ${playerIcon} does nothing to ${opponentIcon}.`;

    /*
    Outcome is determined by player and opponent numbers, the syntax is a chained
    ternary -- it's an abbreviated "if/else if/else" statement:
    ¹If player equals opponent return D(raw)
    ²Else if player equals opponent +1 return W(ins)
    ³Else if player is 0 and opponent is 2 return W(ins)
    ⁴Else return L(ost)
    */
    let outcome = player === opponent ? D : // ¹
      player === opponent + 1 ? W : // ²
      player === 0 && opponent === 2 ? W : L; // ³ : ⁴

    // Reference all form controls (everything except the <label>s) 
    const fc = e.currentTarget.elements;
    // Reference each <output>
    const msg = fc.msg;
    const wins = fc.wins;
    const lost = fc.lost;
    const draw = fc.draw;
    const btns = Array.from(fc.btn);
    const start = fc.start;

    /*
    Pass in the outcome (it's either D, W, or L)
    Each case basically increments the associated score and shows the
    associated message.
    */
    switch (outcome) {
      case D:
        draw.value = ++d;
        msg.value = D;
        break;
      case W:
        wins.value = ++w;
        msg.value = W;
        break;
      case L:
        lost.value = ++l;
        msg.value = L;
        break;
      default:
        break;
    }
    /*
    If turns is less than 1...
    ...display game over message...
    ...show reset <button>...
    ...hide the RPS <button>s...
    ...reset the turns counter scores
    */
    if (turns < 1) {
      msg.value = `5 turns, game over.`;
      start.style.display = 'inline-block';
      btns.forEach(b => b.style.display = 'none');
      turns = 5, w = 0, l = 0, d = 0;
    }
  }
}
// Bind the click event to <form>
rps.onclick = game;

// Bind the reset event to <form>
rps.onreset = e => {
  // Reference all form controls hide reset <button> show RPS <button>s
  const fc = e.currentTarget.elements;
  fc.start.style.display = 'none';
  Array.from(fc.btn).forEach(b => b.style.display = 'inline-block');
}
html {
  font: 300 3ch/1.25 'Segoe UI';
}

form {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

fieldset {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  min-width: 350px;
}

output {
  font-family: Consolas
}

#msg {
  font-family: 'Segoe UI';
}

button {
  font: inherit;
  cursor: pointer;
}

[type="reset"] {
  display: none
}
<form id='rps'>
  <fieldset>
    <legend>Roshambo</legend>
    <button name='btn' type='button' value='0'></button>
    <button name='btn' type='button' value='1'></button>
    <button name='btn' type='button' value='2'>✂️</button>
    <button id='start' type='reset'>Play Again</button>
  </fieldset>
  <fieldset>
    <output id='msg'>&nbsp;</output>
  </fieldset>
  <fieldset>
    <label>Wins: <output id='wins'>0</output></label>
    <label>Lost: <output id='lost'>0</output></label>
    <label>Draw: <output id='draw'>0</output></label>
  </fieldset>
</form>