Home > Software design >  Rock Paper Scissors declare winner logic
Rock Paper Scissors declare winner logic

Time:01-23

I'm trying to code a simple Rock Paper Scissors game with three images that the player clicks on to trigger an event listener and initiate the start of the game playGame().
Where I'm running into problems with my second function, declareWinner() which should evaluate the if/else statements and user and computer selection and declare the winner. I think the issue is with the userInput but I don't know what the problem is. Each time the game runs it skips to the else statement and console.logs "It's a tie.".
What am I doing wrong?

Here is my HTML and CSS

//Initialize scores to zero
let yourScore = 0;
let computerScore = 0;
let roundNum = 0;
let userInput;
let computerInput;

//Global Variables
const userRock = document.querySelector(".user-rock");
const userPaper = document.querySelector(".user-paper");
const userScissors = document.querySelector(".user-scissors");
const computerRock = document.querySelector(".computer-rock");
const computerPaper = document.querySelector(".computer-paper");
const computerScissors = document.querySelector(".computer-scissors");
const scoreUser = document.querySelector(".user-score");
const scoreComputer = document.querySelector(".computer-score");


let computerSelection = document.getElementById("computer-selection");
          
// Adding event listener to User icons
userRock.addEventListener("click", playGame);
userPaper.addEventListener("click", playGame);
userScissors.addEventListener("click", playGame);

// Create playGame() to start game when image is clicked
function playGame (){
    let computerInput = Math.floor(Math.random() * 4);
        if (computerInput === 1) {
            computerInput === 'rock'
            console.log ("computer chose rock");
        }
        if (computerInput === 2) {
            computerInput === 'paper'        
            console.log ("computer chose paper");
        }
        if (computerInput === 3) {
            computerInput === 'scissors'
            console.log ("computer chose scissors");
        }
    evaluateRound(userInput, computerInput);
}

    function evaluateRound(userInput, computerInput) {
        if(userInput === 'rock' && computerInput === 'paper') {
            console.log ('You lose! Paper beats rock!'); 
            scoreComputer.innerHTML = scoreComputer  ;    
        } if (userInput === 'rock' && computerInput === 'rock') {
            console.log ('Its a tie!');     
        } if (userInput === 'rock' && computerInput === 'scissors') {
            console.log ('You win! Rock beats scissors!');
            scoreUser.innerHTML = scoreUser  ;      
        // User Chooses Paper
        } else if(userInput === "paper" && computerInput === 'rock') {
            console.log ('You win! Rock beats paper!');   
            scoreUser.innerHTML = scoreUser  ;     
        } else if (userInput === 'paper' && computerInput === 'paper') {
            console.log ('Its a tie!');     
        } else if (userInput === 'paper' && computerInput === 'scissors') {
            console.log ('You lose! Scissors beats paper!'); 
            scoreComputer.innerHTML = scoreComputer  ;    
        // User Chooses Scissors
        } else if(userInput === "scissors" && computerInput === 'rock') {
            console.log ('You lose! Rock beats scissors!');     
            scoreComputer.innerHTML = scoreComputer  ; 
        } else if (userInput === 'scissors' && computerInput === 'paper') {
            console.log ('You win! Scissors beats paper!'); 
            scoreUser.innerHTML = scoreUser  ;      
        } else {
            console.log ('It"s a tie!');  
        }  
    }

and

<!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">
    <link rel="stylesheet" href="index.css"> 
    <title>Rock Paper Scissors</title>
    <h1> Rock Paper Scissors</h1>
    <h2> The first player to get <span>5 points</span> wins!</h2>

    <p>SCORE:</p> 
   
    <div >
        <div >0</div>  
        <div >0</div>  
    </div>

    <div >    
        <div >
            <div >You chose:<div ></div>
            <div >
                <div >
                    <img class ="user-rock" src="rock.jpg" height="60px"></img>
                    <h3>Rock</h3>
                </div>
                <div >
                    <img  src="paper.jpg" height="60px"></img>
                    <h3>Paper</h3>
                </div>
                <div >
                    <img  src="scissors.jpg" height="60px"></img>
                    <h3>Scissors</h3>
                </div>
            </div>
            </div>
        </div>
    
        <div >
            <div >Computer chose:<div ></div>
            <div >
                <div >
                    <img  src="rock.jpg" height="60px"></img>
                    <h3>Rock</h3>
                </div>
                <div >
                    <img  src="paper.jpg" height="60px"></img>
                    <h3>Paper</h3>
                </div>
                <div >
                    <img  src="scissors.jpg" height="60px"></img>
                    <h3>Scissors</h3>
                </div>
            </div>
            </div>
        </div>
  

</head>
<body>
    <script src="index.js"></script>
</body>
</html>

CodePudding user response:

  • Your indexes logic is wrong Math.floor(Math.random() * 4) can give you 0,1,2,3 — but you only need 0,1,2.
  • The document tags that are part of your app should go in <body>, not in <head>

Also given Rock Paper Scissors is actually a game of indexes, you could convert your logic to something more simpler:

const fig = ["Rock", "Paper", "Scissors"];
const msg = ["You won", "You lost", "It's a draw"];
const score = [0, 0, 0]; // 0= PL's score,  1= AI's score, 2=Total Draws

function play() {
  const PL = Number(this.dataset.player);   // Get 0, 1, 2 from button data-player
  const AI = Math.floor(Math.random() * 3); // Generate random 0, 1, 2 integer

  let res; // Result to be determined:

  if (PL === AI) {
    res = 2;  // Draw
  } else if ((AI   1) % 3 === PL) {
    res = 0;  // Player wins
  } else {
    res = 1;  // Computer wins
  }
  
  score[res]  = 1;

  console.log(`
    ${msg[res]} 
    You played: ${fig[PL]}
    Computer played: ${fig[AI]} 
    Score: Player: ${score[0]} Computer: ${score[1]} Draws: ${score[2]}
  `);
}

document.querySelectorAll("[data-player]").forEach((el) => {
  el.addEventListener("click", play);
});
<button data-player="0" type="button">ROCK</button>
<button data-player="1" type="button">PAPER</button>
<button data-player="2" type="button">SCISSORS</button>

Let's examine the key concept of "RPS is a game if indexes".

The easiest logic is when PL equals AI. So having that one eliminated,
Player wins if: we add 1 to AI's result and after a Modulo %3 the values are equal. The last one possibility is: Computer has won.

Why the modulo logic works is because of the order R-P-S or 0 1 2, which is a linear wins-over sequence.

// Rock Paper Scissors - win logic:

 ...  0R  1P  2S  ...  wins over:
     /   /   /   /    
    /   /   /   /
 ...  0R  1P  2S  ...

by using % 3 (in the (AI 1) % 3) we're just making sure to cover the above's ... cases.

Without the if, else the above can be also rewritten using the (Conditional) Ternary Operator statement ? ifTrue : ifFalse :

const fig = ["Rock", "Paper", "Scissors"];
const msg = ["You won", "You lost", "It's a draw"];
const score = [0, 0, 0];

function play() {
  const PL = Number(this.dataset.player);   // Get 0, 1, 2 from button data-player
  const AI = Math.floor(Math.random() * 3); // Generate random 0, 1, 2 integer
  let res = PL === AI ? 2 : (AI   1) % 3 === PL ? 0 : 1; // Determine result
  score[res]  = 1;
  console.log(`
    ${msg[res]}!
    You played: ${fig[PL]},
    Computer played: ${fig[AI]}
    Score: Player: ${score[0]} Computer: ${score[1]} Draws: ${score[2]}
  `);
}

document.querySelectorAll("[data-player]").forEach(el => el.addEventListener("click", play));
<button data-player="0" type="button">ROCK</button>
<button data-player="1" type="button">PAPER</button>
<button data-player="2" type="button">SCISSORS</button>

CodePudding user response:

I defined userInput and kept my if/else statements and now it works. Will work on refactoring my code and trying different simpler types of logic next. thanks for everyone who looked at my code!

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

function playRound(userInput) {
    const computerInput = getComputerChoice();

if(userInput === 'rock' && computerInput === 'paper') {
        computerScore  ; 
        computerScore_div.innerHTML = computerScore;
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    } if (userInput === 'rock' && computerInput === 'rock') {
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput; 
    } if (userInput === 'rock' && computerInput === 'scissors') {
        userScore  ;    
        userScore_div.innerHTML = userScore;
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    // User Chooses Paper
    } else if(userInput === "paper" && computerInput === 'rock') {
        userScore  ;     
        userScore_div.innerHTML = userScore;
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    } else if (userInput === 'paper' && computerInput === 'paper') {
        console.log ('You chose paper and computer chose paper. It"s a tie!');     
    } else if (userInput === 'paper' && computerInput === 'scissors') {
        computerScore  ;   
        computerScore_div.innerHTML = computerScore;
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    // User Chooses Scissors
    } else if(userInput === "scissors" && computerInput === 'rock') {
        computerScore  ;
        computerScore_div.innerHTML = computerScore;
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    } else if (userInput === 'scissors' && computerInput === 'paper') {
        userScore  ;     
        userScore_div.innerHTML = userScore;
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    } else {
        userSelection_div.innerHTML = "You chose "   userInput;
        computerSelection_div.innerHTML = "Computer chose "   computerInput;
    }  

}

function playGame() {
    userRock.addEventListener("click", function () {
        playRound("rock");
    })
    userPaper.addEventListener("click", function () {
        playRound("paper");
    })
    userScissors.addEventListener("click", function () {
        playRound("scissors");
    })
}

playGame();


  •  Tags:  
  • Related