skip to Main Content

Here’s my JS and HTML. I want to add the playGame() function to my playground function to include rounds. Also, I want to display the winner of the game after 5 rounds without having to click one of my rock, paper, scissors buttons.

This is my code snippet.

const rock = document.querySelector("#rock").addEventListener("click", function() {
  let result = playRound("rock", getComputerChoice());
  console.log(result);
});

const scissors = document.querySelector("#scissors").addEventListener("click", function() {
  let result = playRound("scissors", getComputerChoice());
  console.log(result);
});

const paper = document.querySelector("#paper").addEventListener("click", function() {
  let result = playRound("paper", getComputerChoice());
  console.log(result);
});



function getComputerChoice() {
  const choices = ["rock", "paper", "scissors"];
  let computerChoice = choices[Math.floor(Math.random() * 3)];
  return computerChoice;
}

const rounds = 5;
let playerScore = 0;
let computerScore = 0;

function playRound(playerSelection, computerSelection) {


  if (playerSelection === computerSelection) {
    return "It's a tie";
  } else if (
    (playerSelection === "rock" && computerSelection === "scissors") ||
    (playerSelection === "paper" && computerSelection === "rock") ||
    (playerSelection === "scissors" && computerSelection === "paper")
  ) {
    playerScore++;
    return `Player wins! ${playerSelection} beats ${computerSelection}`;
  } else {
    computerScore++;
    return `Computer wins! ${computerSelection} beats ${playerSelection}`;
  }
}


function playGame() {
  for (let i = 0; i < rounds; i++) {
    if (playerScore > computerScore) {
      return "Player wins the game";
    } else if (computerScore > playerScore) {
      return "Computer wins the game"
    } else {
      return "Game ends in a tie"
    }
  }
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="script.js" defer></script>
  <link rel="stylesheet" href="style.css">
  <title>Rock Paper Scissors</title>
</head>

<body>
  <div class="container">
    <button id="rock">Rock</button>
    <button id="paper">Paper</button>
    <button id="scissors">Scissors</button>
  </div>

  <p id="result"></p>
  </p>


</body>

</html>

Looking for guidance.

2

Answers


  1. You’ve done a nice job.

    There are lots of different ideas in this code – I hope you find it interesting and helpful.

    // Play until either the computer or player wins 3 rounds
    const MAX_ROUNDS = 3;
    
    // Translation text to digit
    const TEXT_TO_INT = {
      rock: 0,
      paper: 1,
      scissors: 2
    };
    
    // Set up the outcome determination using a two-dimensional array 
    // Using a single character would save space, but this is easier to work with
    const COMPUTER = 'computer';
    const PLAYER = 'player';
    const TIE = '(tie)';
    
    // Row is computer's choice, column is player's choice
    // OUTCOME[1,2] means computer chose paper, player chose scissors
    const OUTCOME = [
      [TIE, PLAYER, COMPUTER],
      [COMPUTER, TIE, PLAYER],
      [PLAYER, COMPUTER, TIE]
    ];
    
    function determineWinner(computer, player) {
      return OUTCOME[computer][player];
    }
    
    const ROCK = document.getElementById("rock");
    const PAPER = document.getElementById("paper");
    const SCISSORS = document.getElementById("scissors");
    const RESULT = document.getElementById("result");
    const BUTTONS = document.getElementById("buttons");
    
    // The score is stored as an object
    const score = {
      'computer': 0,
      'player': 0
    }
    
    // Use a single function to handle all the button clicks
    function clickHandler(e) {
      // Get the computer's choice
      const computer = Math.floor(Math.random() * 3);
    
      // Get the players choice from the button id
      // Translate the player's choice from text to integer
      const player = TEXT_TO_INT[e.target.id];
    
      const result = determineWinner(computer, player);
    
      RESULT.textContent = result;
      // If the outcome is a tie, ignore it
      if (result !== TIE) {
        // Update the result display and increment the score of the winner
        document.getElementById(result).textContent = ++score[result];
        if (score.computer >= MAX_ROUNDS || score.player >= MAX_ROUNDS) {
          // The most recent result indicates the winner
          RESULT.textContent = `Game over ${result} wins!`;
          // Remove the event handler to end the game
          BUTTONS.removeEventListener("click", clickHandler);
        }
      }
    }
    
    // Handle game play
    BUTTONS.addEventListener("click", clickHandler);
    <div id="buttons">
      <button id="rock">Rock</button>
      <button id="paper">Paper</button>
      <button id="scissors">Scissors</button>
    </div>
    <label for="result">Result</label> <output id="result"></output><br>
    
    <label for="computer">Computer wins</label> <output id="computer"></output><br>
    <label for="player">Player wins</label> <output id="player"></output><br>
    Login or Signup to reply.
  2. A for loop (your current approach) won’t work for this because the interpreter will zoom through the code, not waiting for the user to press a button (technically, you could make it work using promises and async/await, but that is really confusing – especially for a new programmer).

    Instead, make a variable called currentRound to store what round it is. Then, in your playRound function, add code that checks if currentRound > rounds and then calculates winner.

    Here is an example program showing how to implement this (Note that it resets the game after calculating winner, but this is not necessary).

    // global variables
    let currentRound = 1;
    let maxRounds = 5;
    let humanScore = 0;
    let computerScore = 0;
    
    // look up DOM elements
    let rock = document.querySelector("#rock");
    let paper = document.querySelector("#paper");
    let scissors = document.querySelector("#scissors");
    let round = document.querySelector("#round");
    let human = document.querySelector("#human");
    let computer = document.querySelector("#computer");
    let result = document.querySelector("#result");
    
    // event listeners for button elements
    rock.addEventListener("click", function() {
      playRound("rock", makeComputerMove());
    });
    paper.addEventListener("click", function() {
      playRound("paper", makeComputerMove());
    });
    scissors.addEventListener("click", function() {
      playRound("scissors", makeComputerMove());
    });
    
    // make computer move function
    function makeComputerMove() {
      let moves = ["rock", "paper", "scissors"]; // possible moves
      let move = Math.floor(Math.random() * 3); // generate random move
      return moves[move];
    }
    
    // play round function
    function playRound(humanMove, computerMove) {
    
      // if game needs to be reset (currentRound has been set to -1 at line 83)
      if (currentRound == -1) {
      
        // reset
        round.innerText = '1';
        human.innerText = '0';
        computer.innerText = '0';
        result.innerText = `Click rock, paper, or scissors to play`;
        
        // make this code to be skipped next time
        currentRound = 1;
        return;
      }
      
      // moves are the same
      if (humanMove == computerMove) {
      
        // tie
        result.innerText = `Tie, ${humanMove} is the same as ${computerMove}`;
        return;
        
      // cases where human wins
      } else if ((humanMove == "rock" && computerMove == "scissors") ||
          (humanMove == "paper" && computerMove == "rock") ||
          (humanMove == "scissors" && computerMove == "paper")) {
        
        // human wins
        humanScore++;
        result.innerText = `Human wins, ${humanMove} beats ${computerMove}`;
        
      // otherwise
      } else {
      
        // computer wins
        computerScore++;
        result.innerText = `Computer wins, ${computerMove} beats ${humanMove}`;
      }
      
      // show messages
      round.innerText = currentRound.toString();
      human.innerText = humanScore;
      computer.innerText = computerScore;
      
      
      // increment this round
      currentRound++;
      
      // 5 rounds past
      if (currentRound > 5) {
        // calculate winner
        let winner = humanScore > computerScore ? "human" : "computer";
        result.innerText = `Game over, ${winner} wins! (computer move: ${computerMove}, human move: ${humanMove}) - Click any button to restart`
        
        // reset
        currentRound = -1; // allows reset to happen
        humanScore = 0;
        computerScore = 0;
      }
    }
    html, body {
      font-family:monospace;
    }
    h2 {
      color:turquoise;
    }
    button {
      border:0;
      border-radius:5px;
      padding:5px 10px;
      margin:2px 0px;
      width:100px;
      cursor:pointer;
      background:turquoise;
    }
    button:hover {
      box-shadow:1px 1px 4px 0px black;
    }
    <!DOCTYPE html>
    <html>
    <head>
      <title>Rock Paper Scissors game </title>
    </head>
    <body>
      <div class="game">
        <h2>Rock Paper Scissors</h2>
        <p>
          <span>Round: <span><span id="round">1</span><br>    
          <span>Human score: <span><span id="human">0</span><br>      
          <span>Computer score: <span><span id="computer">0</span><br>   
          <span>Result:  <span><span id="result">Click rock, paper, or scissors to play</span><br>           
        </p>
        <button id="rock">Rock</button><br>
        <button id="paper">Paper</button><br>
        <button id="scissors">Scissors</button><br>
        <p id="result"></p>
      </div>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search