Currently, I'm in the process of developing a rock-paper-scissors game that utilizes prompts for player input. Below is the full code snippet:
var options = ['R','P','S','r','p','s']
var userRes;
var checkVar;
var compChoice;
var checkStat;
var winStat = 0;
var lossStat = 0;
var tieStat = 0;
function isValid() {
for (var i = 0; i < options.length; i++) {
const found = options[i];
if (userRes === found) {
return checkVar = true;
} else if (userRes !== found) {
return checkVar = false;
}
}
}
function getCompChoice() {
let compSet = options[Math.floor(Math.random() * options.length)];
compChoice = compSet.toUpperCase();
console.log(compChoice)
return alert('The computer chose ' + compChoice);
}
function getUserChoice () {
userSet = prompt('Rock Paper or Scissors?');
if (userSet === null) {
return startGame();
} else {
userRes = userSet.toUpperCase();
}
isValid()
if (checkVar === true) {
console.log('continue')
userRes.toUpperCase();
console.log(userRes);
getCompChoice()
if((userRes === 'R' && compChoice === 'S') ||
(userRes === 'P' && compChoice === 'R' ||
(userRes === 'S' && compChoice === 'P'))) {
console.log('win')
alert('You Won !')
checkStat = true
playAgain()
} else if (userRes === compChoice) {
console.log('tie')
alert('You Tied !')
checkStat = null
playAgain()
} else if (userRes !== compChoice) {
console.log('loss')
alert('You Lost !')
checkStat = false
playAgain()
}
} else if (checkVar === false) {
console.log('end')
console.log(userRes);
alert('Please enter R, P, or S. (Not case sensitive).');
getUserChoice();
}
}
function playAgain() {
if (checkStat) {
winStat++;
alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
} else if (checkStat === null){
tieStat++;
alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
} else if (!checkStat) {
lossStat++;
alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
}
pAgain = confirm('Play Again ?')
if (pAgain) {
getUserChoice();
}
}
function startGame () {
askUser = confirm('Would you like to play a game of Rock, Paper, Scissors ?')
if (askUser) {
return getUserChoice();
} else if (!askUser) {
return alert('Come back next time !')
}
}
startGame();
An issue I am facing right now is that the function isValid()
only runs once and outputs just 'R' in my console log. This disrupts the functionality of the game, as I can only use 'r' to play. Trying 'S' or 'P' triggers an alert stating I did not enter 'r', 'p', or 's'. If anyone could help me understand why the loop is only running once or why it's only outputting 'R', I would greatly appreciate it. I've been stuck on this problem for quite some time.
Just so you know, I am still relatively new to JavaScript.
I attempted to use a const to convert my array to string outputs in the console, but that did not yield any results.