Rock Paper Scissors game Javascript, how to troubleshoot - javascript

Currently doing a rock paper scissors tutorial and can't see where I forgot to do something because the userChoice and the computerChoice are showing, but still the result doesn't show up.
I'm currently learning and really can't figure out where is my mistake
const computerChoiceDisplay = document.getElementById('computer-choice')
const userChoiceDisplay = document.getElementById('user-choice')
const resultDisplay = document.getElementById('resut')
const possibleChoices = document.querySelectorAll('button')
let computerChoice
let userChoice
let result
possibleChoices.forEach(possibleChoice => possibleChoice.addEventListener('click', (e) => {
userChoice = e.target.id
userChoiceDisplay.innerHTML = userChoice
generateComputerChoice()
getResult()
}))
function generateComputerChoice(){
const randomNumber = Math.floor(Math.random() * possibleChoices.length) + 1 //or 3
if (randomNumber === 1) {
computerChoice='rock'
}
if (randomNumber === 2){
computerChoice='scissors'
}
if (randomNumber === 3){
computerChoice='paper'
}
computerChoiceDisplay.innerHTML = computerChoice
}
function getResult(){
if (computerChoice === userChoice){
result = 'its a draw!'
}
if (computerChoice === 'rock' && userChoice === 'paper'){
result = 'you win!'
}
if (computerChoice === 'rock' && userChoice === 'scissors'){
result = 'you lost!'
}
if (computerChoice === 'paper' && userChoice === 'scissors'){
result = 'you win!'
}
if (computerChoice === 'paper' && userChoice === 'rock'){
result = 'you lost!'
}
if (computerChoice === 'scissors' && userChoice === 'rock'){
result = 'you win!'
}
if (computerChoice === 'scissors' && userChoice === 'paper'){
result = 'you lost!'
}
resultDisplay.innerHTML = result
}

Related

getResult is Undefined

I can't seem to find out what is creating this undefined error in my basic rock paper scissor game it gives me to results instead of just one I'm trying to understand javascript its just taking me time to really grasp the in and outs of it if anyone can solve this for me and explain where I went wrong I'd really appreciate it
<!DOCTYPE html>
<head>
<title>Rock, Paper, Scissors</title>
<link rel="stylesheet" type="text/css" href="./css/reset.css">
<link rel="stylesheet" type="text/css" href="./css/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<h2>User Choice: <span id="user-choice"></span></h2>
<h2>Computer Choice: <span id="computer-choice"></span></h2>
<h2>Result: <span id="result"></span></h2>
<button id="Rock">Rock</button>
<button id="Paper">Paper</button>
<button id="Scissors">Scissors</button>
<script src="rock.js"></script>
</body>
</html>
const computerChoiceDisplay = document.getElementById ("computer-choice")
const userChoiceDisplay = document.getElementById("user-choice")
const resultDisplay = document.getElementById("result")
const possibleChoices = document.querySelectorAll("button")
let userChoice
let computerChoice
let result
possibleChoices.forEach(possibleChoices => possibleChoices.addEventListener('click', (e) => {
userChoice = e.target.id
userChoiceDisplay.innerHTML = userChoice
generateComputerChoice()
getResult()
}))
function generateComputerChoice() {
const randomNumber = Math.floor(Math.random() * 3) + 1 // or you can use possibleChoices.length
if(randomNumber === 1) {
computerChoice = 'rock'
}
if(randomNumber === 2) {
computerChoice = 'scissors'
}
if(randomNumber === 3) {
computerChoice = 'paper'
}
computerChoiceDisplay.innerHTML = computerChoice;
}
function getResult() {
if (userChoice === 'rock' && computerChoice === 'paper') {
result = 'you win!'
}
if (userChoice === 'scissor' && computerChoice === 'rock') {
result = 'you win!'
}
if (userChoice === 'paper' && computerChoice === 'scissors') {
result = 'you win!'
}
if (userChoice === 'rock' && computerChoice === 'scissors') {
result = 'you lost!'
}
if (userChoice === 'scissors' && computerChoice === 'paper') {
result = 'you lost!'
}
if (userChoice === 'paper' && computerChoice === 'rock') {
result = 'you lost!'
}
if (userChoice === computerChoice) {
result = `its a draw!`
}
resultDisplay.innerHTML = result
console.log(getResult)
}
The conditions inside the getResult() function never gets true because the string values compared inside if conditions doesn't match.
The string value equaled to userChoice is lowercase and the string value which you actually get through userChoice is Title case(First letter capital). So the strings doesn't match and result variable never gets assigned. Hope this helps!
function getResult() {
if (userChoice == 'Rock' && computerChoice == 'paper') {
result = 'you win!';
}
if (userChoice == 'Scissors' && computerChoice == 'rock') {
result = 'you win!'
}
if (userChoice == 'Paper' && computerChoice == 'scissors') {
result = 'you win!'
}
if (userChoice == 'Rock' && computerChoice == 'scissors') {
result = 'you lost!'
}
if (userChoice == 'Scissors' && computerChoice == 'paper') {
result = 'you lost!'
}
if (userChoice == 'Paper' && computerChoice == 'rock') {
result = 'you lost!'
}
if (userChoice == computerChoice) {
result = 'its a draw!'
}
resultDisplay.innerHTML = result
console.log(getResult)
}

Conditional statement returns same result regardless of outcome

I'm trying to manipulating the DOM to show who wins when playing Rock paper scissors game. I'm targeting a <p class="result" to do this. But it doesn't matter what the result is, "it's a Draw" is only displayed. Please help!
On a side note, if any one has any suggestions on how to refactor this due to the multiple lines of "player wins", "Computer wins" code, then please let me know.
for (var i = 0; i < document.querySelectorAll("button").length; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
var playerChoice = (this.innerHTML);
var random = Math.floor(Math.random() * document.querySelectorAll("button").length);
var compChoice = ["Rock", "Paper", "Scissors"]
document.querySelector(".player").innerHTML = playerChoice;
document.querySelector(".computer").innerHTML = compChoice[random]
if (playerChoice === "Rock" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Paper" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Paper" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Rock" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === compChoice) {
document.querySelector(".result").innerHTML = "It's a draw";
}
console.log(playerChoice);
})
}
https://ibb.co/44Z1vQ3
Brandom's idea in the comments above to console.log playerChoice helped me realise a way to problem solve this by also console logging compchoice which returns an array, so i needed to encapsulate the compChoice[random] into a variable first shown below.
It is now all working as it should.
for (var i = 0; i < document.querySelectorAll("button").length; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
var playerChoice = (this.innerHTML);
var random = Math.floor(Math.random() * document.querySelectorAll("button").length);
var choices = ["Rock", "Paper", "Scissors"]
var compChoice = choices[random]
document.querySelector(".player").innerHTML = playerChoice;
document.querySelector(".computer").innerHTML = compChoice;
if (playerChoice === "Rock" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Paper" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Paper" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Rock" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === compChoice) {
document.querySelector(".result").innerHTML = "It's a draw";
}
console.log(playerChoice);
console.log(compChoice);
})
}

How can I loop the function playRound()?

I am building my first rock paper scissors game. I have not formally done loops as yet but I am trying to apply a for loop to the playRound function so it plays five times. Sadly I am not certain where to apply it. I have tried a few ways but keep getting errors. Anyone able to take a look and provide an option. code is below.
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
}
if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
playerSelection = "rock";
computerSelection = computerPlay();
if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")
) {
return "Player Wins!";
} else if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
If I understood correctly what you want, you can do a while loop with a counter, also I improved a bit your code, making strict equality (from == to ===), and removed redundant code
let counter = 1;
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
} else if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
counter++;
if (
(playerSelection === "rock" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "paper") ||
(playerSelection === "paper" && computerSelection === "rock")
) {
return "Player Wins!";
} else if (
(playerSelection === "rock" && computerSelection == "paper") ||
(playerSelection === "paper" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
while (counter < 6) {
console.log(playRound(playerSelection, computerPlay()));
}
Hope this example gives some hint on how to do good programming
// rock = 0
// paper = 1
// scissor = 2
const valueMap = {
0: 'rock',
1: 'paper',
2: 'scissor'
}
function pick() {
return Math.floor(Math.random() * 3)
}
function decide(p1, p2) {
const pool = [p1, p2]
const sortedPool = pool.sort((a, b) => b.value - a.value)
const diff = sortedPool[0].value - sortedPool[1].value
if (diff === 2) {
return sortedPool[1].name
} else if (diff === 0) {
return 'draw'
} else {
return pool.find(v => v.value === sortedPool[0].value).name
}
}
function play(times, cb) {
let n = 1
while (n <= times) {
cb(n)
n++
}
}
play(5, function(n) {
const player1 = {
name: 'Player',
value: pick()
}
const player2 = {
name: 'Computer',
value: pick()
}
const result = decide(player1, player2)
console.log(
`Game ${n}`,
`${player1.name} ${valueMap[player1.value]}`,
` vs `,
`${player2.name} ${valueMap[player2.value]}`,
`>>> Winner ${result}
`
)
})
Add loop for last 3 line
for (i=0; i<5; i++){
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
}
Edit: Please note that you have redundant call function computerPlay() inside playRound function since computer selection is passed in second argument

how can my if statement not work even though I fill out the prompt() correct

So I am making a little rock, paper and scissors game in which you play VS the computer.
However, I made an if statement that should check whether you have filled out 'rock, paper or scissors'. If not, it should return an alert() that you did NOT fill out one of these 3, however when I do fill out rock, paper or scissors it still returns the alert().
The function:
function rockPaperScissors() {
let computerChoice;
let loopFunction = false;
let draw = 0;
while (loopFunction === false) {
let playerGuess = prompt('Enter rock, paper or scissors!');
let computerChoiceCalculator = Math.floor(Math.random() * 10);
if (playerGuess == '') {
window.alert('ggggg');
return;
} else if (playerGuess != 'rock' || 'paper' || 'scissors') {
window.alert('Please enter rock, paper or scissors');
}
else {
if (computerChoiceCalculator <= 4) {
computerChoice = 'rock';
console.log(computerChoice);
} else if (computerChoiceCalculator <= 7) {
computerChoice = 'paper';
console.log(computerChoice);
} else {
computerChoice = 'scissors';
console.log(computerChoice);
}
if (playerGuess === computerChoice) {
draw += 1;
window.alert('THIS WAS A DRAW! THE COMPUTER HAD ' + computerChoice + ' AND U HAD ' + playerGuess);
} else if (playerGuess === 'rock' && computerChoice === 'paper' || playerGuess === 'paper' && computerChoice === 'scissors' || playerGuess === 'scissors' && computerChoice === 'rock') {
window.alert('The computer won this round! Lets try again! your try was ' + playerGuess + ' and the computer had ' + computerChoice);
} else {
window.alert('fuck yeah! u won!');
}
}
}
}
the code which causes the problem:
else if (playerGuess != 'rock' || 'paper' || 'scissors') {
window.alert('Please enter rock, paper or scissors');
}
Ohh this is wrong:
else if (playerGuess != 'rock' || 'paper' || 'scissors')
This conditional won't work because you can't group equality operators like this.
You have to make the comparison for each item. This conditional, as written, will always return true because 'paper' will always be a truthy value.
You should do this instead:
else if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors')
Or you could do this, which is prettier:
else if (!['rock', 'paper', 'scissors'].includes(playerGuess))
you can't use this form of if statement else if (playerGuess != 'rock' || 'paper' || 'scissors')
it should be devided into three different comparasions like this:
else if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors')
you should replace it with :
if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors') {
or
if(!['rock','paper','scissors'].includes(playerGuess))
As others have suggested, else if (playerGuess != 'rock' || 'paper' || 'scissors') is incorrect syntax.
However, I think this syntax is probably the most modern and readable:
else if (!['rock', 'paper', 'scissors'].includes(playerGuess))

Run outside variable from inside a function

if result is tie i need to run this code again by asling "Do you choose rock, paper or scissors?"
but there's a wrong with this code.
after this Massage "The result is a tie! Would you like to play new game?(yes or no)", i used "compare(userChoice, computerChoice);" to run again this code. its not working.
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
var compare = function(choice1, choice2)
{
if (choice1 === choice2) {
var newChoice = prompt ("The result is a tie! Would you like to play new game?(yes or no)");
if ( newChoice === "yes"){
compare(userChoice, computerChoice);
}
else {
return "Have a nice day!";
}
}
else if (choice1 === "rock"){
if (choice2 === "scissors") {
return ("rock wins")}
else {
return ("paper wins")}
}
else if (choice1 === "paper"){
if (choice2 === "rock") {return ("paper wins");}
else {return ("scissors wins");}
}
else if (choice1 === "scissors"){
if (choice2 === "paper") {return ("scissors wins");}
else {return (" rock wins");}
}
};
compare(userChoice, computerChoice);
Well yes, that's because you call again
compare(userChoice, computerChoice);
at the forth line inside compare function.
try this:
var choices = ['rock', 'paper', 'scissors'];
var makeRandom = function() {
return parseInt(Math.random()*3);
}
function game() {
var userChoice = prompt("Do you choose rock, paper or scissors?");
var index = choices.indexOf(userChoice);
if(index === -1) {
var bl = confirm('Your choice is outof range, would you like to play Again?');
if(bl) game();
}
var computerChoice = makeRandom();
if(index === computerChoice) {
var bl = confirm('It is a tie, would you like to play Again?');
if(bl) { game(); }
} else if((index === 0 && computerChoice === 1) || (index === 1 && computerChoice === 2) || (index === 2 && computerChoice === 0)) {
alert('you loose');
} else {
alert('you win');
}
}
game();

Categories

Resources