getResult is Undefined - javascript

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)
}

Related

Rock Paper Scissors game Javascript, how to troubleshoot

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
}

How to store and update score in the game?

How can I create a function and make it work so that it stores the win case every time user or computer wins?
How can I create a function and make it work so that it stores the win case every time user or computer wins?How can I create a function and make it work so that it stores the win case every time user or computer wins?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Rock Paper Scissors Tutorial</title>
</head>
<body>
<h2>Computer Choice: <span id="computer-choice"></span></h2>
<h2>Your Choice: <span id="user-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>
<br>
<br>
<input type="button" value="Reload Page" onClick="document.location.reload(true)">
<br>
<br>
<div class="results">
<div>
You
<span class="result-score">0</span>
</div>
<div data-final-column>
Computer
<span class="result-score">0</span>
</div>
<script src="main.js"></script>
</body>
</html>
--------------------
js
const computerChoiceDisplay = document.getElementById('computer-choice')
const userChoiceDisplay = document.getElementById('user-choice')
const resultDisplay = document.getElementById('result')
const possibleChoices = document.querySelectorAll('button')
const computerScoreSpan = document.querySelector('[data-computer-score]')
const yourScoreSpan = document.querySelector('[data-your-score]')
let userChoice
let computerChoice
let result
possibleChoices.forEach(possibleChoice => possibleChoice.addEventListener('click', (e) => {
userChoice = e.target.id
userChoiceDisplay.innerHTML = userChoice
generateComputerChoice()
getResult()
}))
// ------
// function incrementScore(scoreSpan) {
// if (yourWinner) incrementScore(yourScoreSpan)
// if (computerWinner) incrementScore(computerScoreSpan)
// scoreSpan.innerText = parseInt(scoreSpan.innerText) + 1
// }
// --------
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 (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 lose!'
}
if (computerChoice === 'scissors' && userChoice === "rock") {
result = 'you win!'
}
if (computerChoice === 'scissors' && userChoice === "paper") {
result = 'you lose!'
}
resultDisplay.innerHTML = result
}
Well for starters your code is really inefficient and messy, and I wouldn't definitely recommend re-starting. But if you want to keep the code you already have, to make the score counter you don't need a function, just add to the score based of the result in the result function.
Here's the updated HTML code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Rock Paper Scissors Tutorial</title>
</head>
<body>
<h2>Computer Choice: <span id="computer-choice"></span></h2>
<h2>Your Choice: <span id="user-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>
<br>
<br>
<input type="button" value="Reload Page" onClick="document.location.reload(true)">
<br>
<br>
<div id="ys">
You: 0
</div>
<div id="cs">
Computer: 0
</div>
<script src="main.js"></script>
</body>
</html>
and your javascript code
const computerChoiceDisplay = document.getElementById('computer-choice')
const userChoiceDisplay = document.getElementById('user-choice')
const resultDisplay = document.getElementById('result')
const possibleChoices = document.querySelectorAll('button')
const cs_t = document.getElementById("cs");
const ps_t = document.getElementById("ys");
let userChoice
let computerChoice
let result
var cs = 0;
var ps = 0;
possibleChoices.forEach(possibleChoice => possibleChoice.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 (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 lose!'
}
if (computerChoice === 'scissors' && userChoice === "rock") {
result = 'you win!'
}
if (computerChoice === 'scissors' && userChoice === "paper") {
result = 'you lose!'
}
if(result == 'you win!'){
ps += 1
}
else if(result == 'you lose!'){
console.log("ok2")
cs += 1
}
else{
cs += 1
ps += 1
}
cs_t.innerHTML = ("Computer: " + cs);
ps_t.innerHTML = ("You: " + ps);
resultDisplay.innerHTML = result
}
also you do not need to put span tags in everything, it's a really bad way of doing it.
from what I understand you want to save the winner of the game somewhere so you can check it later right?
Well, maybe you can use localStorage;
With that, all you gotta do is take the result and store them on localStorage, like this:
localStorage.setItem('result', result);
and for get the result from localStorage, you can save it on a variable:
const checkResult = localStorage.getItem('result') || null
in that way if do not have any results on localStorage, checkResult will return null;

Rock Paper Scissors game issue

I built a very basic rock paper scissors game but it seems that somehow the game is not correctly capturing the userSelection or outputing the correct result...
I've spent hours researching and adjusting various aspects of my code but can't figure it out - I'm too green I guess.
I don't want a totally different version of how to do this -I'd like to fix this version and understand why it doesn't work currently :)
https://codepen.io/anna_whiskey/pen/XWRjQXV
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game() {
function humanPlay() {
document.getElementById("btn1").addEventListener("click", () => {
userSelection = "rock";
})
document.getElementById("btn2").addEventListener("click", () => {
userSelection = "paper";
})
document.getElementById("btn3").addEventListener("click", () => {
userSelection = "scissors";
})
}
function computerPlay() {
computerSel = Math.floor(Math.random() * gameInputs.length);
round1Answer = (gameInputs[computerSel]);
console.log((gameInputs[computerSel]));
humanPlay();
}
computerPlay();
document.getElementById("outcome").textContent = `You: ${userSelection} Computer: ${round1Answer}`
function playRound(round1Answer, userSelection) {
if (userSelection === 'rock' && round1Answer === 'scissors') {
alert('You WIN!');
} else if (userSelection === 'rock' && round1Answer === 'rock') {
alert('It/s a tie!');
} else if (userSelection === 'paper' && round1Answer === 'rock') {
alert('You WIN!');
} else if (userSelection === 'paper' && round1Answer === 'paper') {
alert('It/s a tie!');
} else if (userSelection === 'scissors' && round1Answer === 'paper') {
alert('You WIN!');
} else if (userSelection === 'scissors' && round1Answer === 'scissors') {
alert('It/s a tie!');
} else {
alert('You LOSE!');
}
}
playRound(round1Answer, userSelection);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<title>Rock Paper Scissors</title>
<body>
<div class="bg"></div>
<button id="btn1" onclick="game()">Rock</button>
<button id="btn2" onclick="game()">Paper</button>
<button id="btn3" onclick="game()">Scissors</button>
<div id="outcome"></div>
<link rel="stylesheet" href="rps.css">
<script type="text/javascript" src="rpsv2.js"></script>
</body>
</html>
you should try adding event listeners for human inputs
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game() {
function humanPlay() {
document.getElementById("btn1").addEventListener("click", () => {
userSelection = "rock";
console.log(`User Selection: ${userSelection}`)
})
document.getElementById("btn2").addEventListener("click", () => {
userSelection = "paper";
console.log(`User Selection: ${userSelection}`)
})
document.getElementById("btn3").addEventListener("click", () => {
userSelection = "scissor";
console.log(`User Selection: ${userSelection}`)
})
}
function computerPlay() {
computerSel = Math.floor(Math.random() * 3);
round1Answer = (gameInputs[computerSel]);
// console.log(`Round ans is ${round1Answer}`)
}
function playRound(round1Answer, userSelection) {
if (userSelection == 'rock' && round1Answer == 'scissors') {
alert('You WIN!');
}
else if (userSelection == 'paper' && round1Answer == 'rock') {
alert('You WIN!');
}
else if (userSelection == 'scissors' && round1Answer == 'paper') {
alert('You WIN!');
}
else if (userSelection == 'rock' && round1Answer == 'rock') {
alert('It/s a tie!');
}
else if (userSelection == 'paper' && round1Answer == 'paper') {
alert('It/s a tie!');
}
else if (userSelection == 'scissors' && round1Answer == 'scissors') {
alert('It/s a tie!');
}
else {
alert('You LOSE!');
}
}
humanPlay();
computerPlay();
playRound(round1Answer, userSelection);
}
using this i managed to log rock paper and scissor
You can simple do the task by the following script
JS
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game (humanChoosed) {
userSelection = gameInputs[humanChoosed];
function computerPlay() {
computerSel = Math.floor(Math.random() * gameInputs.length);
round1Answer = (gameInputs[computerSel]);
}
computerPlay();
document.querySelector('h1').textContent = `Human: ${userSelection} Computer: ${round1Answer}`;
function playRound (round1Answer, userSelection) {
if (userSelection === 'rock' && round1Answer === 'scissors') {
alert ('You WIN!');
} else if (userSelection === 'rock' && round1Answer === 'rock') {
alert ('It/s a tie!');
} else if (userSelection === 'paper' && round1Answer === 'rock') {
alert ('You WIN!');
} else if (userSelection === 'paper' && round1Answer === 'paper') {
alert ('It/s a tie!');
} else if (userSelection === 'scissors' && round1Answer === 'paper') {
alert ('You WIN!');
} else if (userSelection === 'scissors' && round1Answer === 'scissors') {
alert ('It/s a tie!');
} else {
alert ('You LOSE!');
}
}
playRound (round1Answer, userSelection);
}
HTML
<body>
<div class="bg"></div>
<button id="btn1" onclick="game(0)">Rock</button>
<button id="btn2" onclick="game(1)">Paper</button>
<button id="btn3" onclick="game(2)">Scissors</button>
<h1>Hello</h1>
<link rel="stylesheet" href="rps.css">
<script type="text/javascript" src="rps.js"></script>
</body>

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

Changing the value of a variable with DOM element click

Im trying to allow the player to click the Rock paper or scissors button and that changes the value of the 'playerChoice' variable so so the playRound function can be called with their choice but it doesnt seem to work and im not sure what im doing wrong
Code
// Rock paper scissors game
let rockBtn = document.querySelector('.Rock');
let paperBtn = document.querySelector('.Paper');
let scissorBtn = document.querySelector('.Scissors');
function computerPlay() {
let rps = ["Rock", "Paper", "Scissors"];
let computerChoice = rps[Math.floor(Math.random()*rps.length)];
return computerChoice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == "Rock" && computerSelection == "Rock") {
console.log('Its a Draw');
} else if (playerSelection == "Rock" && computerSelection == "Scissors") {
console.log("Player wins");
} else if(playerSelection == "Rock" && computerSelection == "Paper") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Paper") {
console.log("Its a draw");
} else if(playerSelection == "Paper" && computerSelection == "Scissors") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Rock") {
console.log("Player wins");
} else if(playerSelection == "Scissors" && computerSelection == "Scissors") {
console.log("Its a draw");
} else if(playerSelection == "Scissors" && computerSelection == "Paper") {
console.log("Player wins ");
} else if(playerSelection == "Scissors" && computerSelection == "Rock") {
console.log("Computer wins");
}
}
function game() {
const computerChoice = computerPlay();
var playerChoice = "";
rockBtn.addEventListener('click' , function() {
playerChoice = "Rock";
});
paperBtn.addEventListener('click' , function() {
playerChoice = "Paper";
console.log(playerChoice);
});
scissorBtn.addEventListener('click' , function() {
playerChoice = "Scissors";
});
console.log("Player choice is" + playerChoice);
console.log('Computer choice is' + computerChoice);
playRound(playerChoice, computerChoice);
}
game();
Is this the correct way to do this is there a better way?
You should call playRound method inside the click listeners.
// Rock paper scissors game
let rockBtn = document.querySelector('.Rock');
let paperBtn = document.querySelector('.Paper');
let scissorBtn = document.querySelector('.Scissors');
var playerChoice = "";
function computerPlay() {
let rps = ["Rock", "Paper", "Scissors"];
let computerChoice = rps[Math.floor(Math.random()*rps.length)];
return computerChoice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == "Rock" && computerSelection == "Rock") {
console.log('Its a Draw');
} else if (playerSelection == "Rock" && computerSelection == "Scissors") {
console.log("Player wins");
} else if(playerSelection == "Rock" && computerSelection == "Paper") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Paper") {
console.log("Its a draw");
} else if(playerSelection == "Paper" && computerSelection == "Scissors") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Rock") {
console.log("Player wins");
} else if(playerSelection == "Scissors" && computerSelection == "Scissors") {
console.log("Its a draw");
} else if(playerSelection == "Scissors" && computerSelection == "Paper") {
console.log("Player wins ");
} else if(playerSelection == "Scissors" && computerSelection == "Rock") {
console.log("Computer wins");
}
playerChoice = "";
}
rockBtn.addEventListener('click' , function() {
playerChoice = "Rock";
playRound(playerChoice, computerPlay());
});
paperBtn.addEventListener('click' , function() {
playerChoice = "Paper";
playRound(playerChoice, computerPlay());
});
scissorBtn.addEventListener('click' , function() {
playerChoice = "Scissors";
playRound(playerChoice, computerPlay());
});

Categories

Resources