jeudi 12 décembre 2019

Why does my function always return the same value?

Newly learning Javascript, so I'm learning to store functions in objects. Currently creating a simple rock,paper, scissors game. I'm stuck, where I need the getWinner function to determine the winner and added 3 conditions to the function = draw, win or lose. Now the problem is, it always returns draw to me. Can anyone help?

const startGameBtn = document.getElementById('start-game-btn');
    
let ROCK = "ROCK";
let PAPER = "PAPER";
let SCISSORS = "SCISSORS";
let RESULT_DRAW = "It's a draw";
let RESULT_PLAYER_WINS = "Player Wins";
let RESULT_COMPUTER_WINS = "Player Wins";
    
let GAME_IS_RUNNING = false;
    
let getPlayerChoice = function () {
    let selection = prompt(`${ROCK},${PAPER}, or ${SCISSORS}? `, '').toUpperCase();
    if (selection !== ROCK &&
        selection !== PAPER &&
        selection !== SCISSORS) {
            alert ("Invalid choice, defaulted to Rock");
            selection = ROCK;
    }
    return selection
}
    
const getComputerChoice = function() {
    const randomValue = Math.floor(Math.random() * 2);
    if (randomValue === 0) {
        return ROCK;
    } else if (randomValue === 1) {
        return PAPER;
    } else if (randomValue === 2) {
        return SCISSORS;
    };
}
    
const getWinner = function (cChoice, pChoice) {
     if (cChoice === pChoice) {
         return RESULT_DRAW;
     } else if (cChoice === ROCK && pChoice === PAPER ||
                cChoice === PAPER && pChoice === SCISSORS ||
                cChoice === SCISSORS && pChoice === ROCK
    ) {
        return RESULT_PLAYER_WINS;
    } else {
        return RESULT_COMPUTER_WINS;
    }
}
    
startGameBtn.addEventListener('click', function () {
    if (GAME_IS_RUNNING) {
        return
    }
    GAME_IS_RUNNING = true;
    console.log("Game is starting....");
    let playerChoice = getPlayerChoice();
    console.log(playerChoice);
    let computerChoice = getComputerChoice();
    console.log(computerChoice);
    let winner = getWinner(computerChoice, playerChoice);
    console.log(winner);
});
<button id="start-game-btn">Start</button>

Aucun commentaire:

Enregistrer un commentaire