Rock paper scissors Javascript - javascript

I'm trying to build an RPS game with Javascript, using a click event as input.
I can get the program to see Watson's input and clock the number of games I've lost, but I can't get the program to recognize my input.
What steps have I missed out? Please check out the following link for all the code including HTML.
https://codepen.io/szewah/pen/daMKbK
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
//gueses
var computerGuess = rockPaperScissors[Math.floor(Math.random()*rockPaperScissors.length)];
var myGuess = function (input) {
if (input === 'Rock' || input === 'Paper' || input === "Scissors") {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins =0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('userchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame () {
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};

// array for choices of rock, paper, scissors
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
function myGuessFn(input) {
if (input === 'Rock' || input === 'Paper' || input === 'Scissors') {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins = 0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('computerchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame(event) {
var myGuess = myGuessFn(event.target.innerHTML);
var computerGuess = rockPaperScissors[Math.floor(Math.random() * rockPaperScissors.length)];
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
#rock-btn,
#paper-btn,
#scissors-btn {
cursor: pointer;
}
<div class="container">
<h1>Press Rock Paper Scissors to play</h1>
<div class="choices">
<div id="rock-btn">Rock</div>
<div id="paper-btn">Paper</div>
<div id="scissors-btn">Scissors</div>
</div>
<hr>
<div class="resultChoice">
<p id="userchoice-text"></p>
<br>
<p id="computerchoice-text"></p>
</div>
<hr>
<div class="results">
<p id="wins-text"></p>
<p id="losses-text"></p>
<p id="ties-text"></p>
</div>
</div>

Related

My code is not running but i have no errors

The project is about making a rock paper scissors game using functions and loops etc.
the code below is how the project looks
the first function is to get the randomized computer choice
the second function is to get the user or players choice
the third function is to play the game and check if the player won or the computer won
the final function is to create a for loop to run the third function a certain number of times to see who is the winner of the game
Been working on it since and have no idea why it doesn't work
```
function getComputerChoice() {
let values = ["rock", "paper", "scissors"];
return values[Math.floor(Math.random() * values.length)];
}
function getPlayerChoice() {
let getChoice = "rock";
let value = getChoice.trim();
let lowCase = value.toLowerCase();
let capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
while (!["Rock", "Paper", "Scissors"].includes(capitalize)) {
value = getChoice.trim();
lowCase = value.toLowerCase();
capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
}
return capitalize;
}
function playRound(playerSelection, computerSelection) {
let games = "";
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return (games =
"player loses!! " + computerSelection + " beats " + playerSelection);
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
return (games =
"player Wins!! " + playerSelection + " beats " + computerSelection);
} else if (playerSelection == computerSelection) {
return (games =
"it a tie noice " + playerSelection + " v " + computerSelection);
} else {
return (games = "euphoria");
}
}
function game() {
let playerScores = 0;
let computerScores = 0;
let computerSelection = "";
let playerSelection = "";
computerSelection = getComputerChoice();
playerSelection = getPlayerChoice();
for (let i = 0; i < 5; i++) {
if (
playRound(
"player loses!! " + computerSelection + " beats " + playerSelection
)
) {
computerScores += 1;
console.log(
"you lost this round!! boo hoo!! scores are " +
computerScores +
" v " +
playerScores
);
} else if (
playRound(
"player Wins!! " + playerSelection + " beats " + computerSelection
)
) {
playerScores += 1;
console.log(
"you Won this round!! hurray!! scores are " +
computerScores +
" v " +
playerScores
);
}
}
if (playerScores > computerScores) {
console.log("congratulations you won this round");
} else if (playerScores < computerScores) {
console.log("im sorry you lost this round");
} else {
console.log("there is a problem");
}
}
game();
```
It doesn't seem that playRound() is returning anything:
function playRound(playerSelection, computerSelection) {
let games = '';
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
games = "player loses!! " + computerSelection + " beats " + playerSelection;
// ADD RETURN HERE
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
games = "player Wins!! " + playerSelection + " beats " + computerSelection;
// ADD RETURN HERE
} else if (playerSelection == computerSelection) {
games = "it a tie noice " + playerSelection + " v " + computerSelection;
// ADD RETURN HERE
} else {
games = "euphoria";
// ADD RETURN HERE
}
}
Explanation
In your game() function definition you are checking if(playRound()). playRound is not returning anything so this is interpreted as a void function, hence, the if will always evaluate to false.

Rock Paper Scissors declare winner logic

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 class="score-board">
<div class="computer-score">0</div>
<div class="user-score">0</div>
</div>
<div class="gameboard">
<div class="user-choices">
<div class="user-instructions">You chose:<div class="user-selection"></div>
<div class="user-icons">
<div class="game-button">
<img class ="user-rock" src="rock.jpg" height="60px"></img>
<h3>Rock</h3>
</div>
<div class="game-button">
<img class="user-paper" src="paper.jpg" height="60px"></img>
<h3>Paper</h3>
</div>
<div class="game-button">
<img class="user-scissors" src="scissors.jpg" height="60px"></img>
<h3>Scissors</h3>
</div>
</div>
</div>
</div>
<div class="computer-choices">
<div class="computer-instructions">Computer chose:<div class="computer-selection"></div>
<div class="computer-icons">
<div class="rock-selection">
<img class="computer-rock" src="rock.jpg" height="60px"></img>
<h3>Rock</h3>
</div>
<div class="paper-selection">
<img class="computer-paper" src="paper.jpg" height="60px"></img>
<h3>Paper</h3>
</div>
<div class="scissors-selection">
<img class="computer-scissors" src="scissors.jpg" height="60px"></img>
<h3>Scissors</h3>
</div>
</div>
</div>
</div>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
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>
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();

JS Game Results Not What I Expect

I'm fairly new to JS and I'm currently trying to make my first simple game. The premise is that the player must choose and submit a bet. They then chose one of three cups and win if the ball is in the chosen cup.
It's mostly functioning as I hoped to except the outcome for how much money they gain.
The player starts with $40 and when its a loss it correctly subtracts the bet amount. When the player wins however it does not add the bet amount but instead puts it beside the previous amount.
For example, if the player has $40 and bets $5 and wins it will change their total to $405.
I have noticed that this does not happen for the first bet if the player wins but then does not work again on subsequent guesses.
I can not figure what is causing this behavior and any help would be greatly appreciated.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Hobo Balls</title>
<link rel="stylesheet" href="hobo.css">
</head>
<body>
<div class="header">
<h1>Hobo Balls</h1>
<h2>Instructions</h2>
</div>
<div class="cups">
<div id="cup1-image">
<img src="/Cup1.png">
</div>
<div id="cup2-image">
<img src="/Cup2.png">
</div>
<div id="cup3-image">
<img src="/Cup3.png">
</div>
</div>
<br>
<div>
<label for="bet">Place Your Bet</label>
<input name="bet" id="bet" type="number" min="1" max="400" value="0"/>
<input id="enter-bet" type="submit"/>
<p id="show-bet"></p>
</div>
<div class="result">
<h3>You are a ???</h3>
<p id="win-or-lose"></p>
</div>
<p id="cash"></p>
<script type="text/javascript" src="/hoboscript.js"></script>
</body>
</html>
JS
let cup1;
let cup2;
let cup3;
let playerGuess;
let playerBet;
let playerCash = 40;
let outcome;
//Player enters bet amount
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").value;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
});
//Determine ball position
const ballPlacement = () => {
const ballResult = Math.floor(Math.random() * 3);
console.log(ballResult);
if (ballResult === 0) {
cup1 = 'ball';
cup2 = 'crab';
cup3 = 'hobo';
} else if (ballResult === 1) {
cup1 = 'crab';
cup2 = 'ball';
cup3 = 'hobo';
} else { (ballResult === 2); {
cup1 = 'hobo';
cup2 = 'crab';
cup3 = 'ball';
}
}
};
//Determine if guess iscorrect and display result
const playerWin = () => {
//correct Guess
if (playerGuess === 'cup1' && cup1 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup1-image').innerHTML = '<img src="/ball.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup2-image').innerHTML = '<img src="/ball.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup3-image').innerHTML = '<img src="/ball.jpg">';
//incorrect guess
} else if (playerGuess === 'cup1' && cup1 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup1-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup1' && cup1 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup1-image').innerHTML = '<img src="/hobo.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup2-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup2-image').innerHTML = '<img src="/hobo.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup3-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup3-image').innerHTML = '<img src="/hobo.jpg">';
}
};
//Player selects cup, previous functions are called
document.getElementById("cup1-image").addEventListener("click", function () {
playerGuess = 'cup1';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
document.getElementById("cup2-image").addEventListener("click", function () {
playerGuess = 'cup2';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
document.getElementById("cup3-image").addEventListener("click", function () {
playerGuess = 'cup3';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
Here in your code:
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").value;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
});
The variable playerBet is being assigned a string value, change the statement to:
playerBet = parseInt(document.getElementById("bet").value;
Use valueAsNumber instead of value for number inputs:
//Player enters bet amount
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").valueAsNumber;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
})

Infinite Loop in JavaScript - While Loop

Does anyone know why this may be causing an infinite loop. I just can't see why!
I feel the issue may be with my while loop under play to five.
The while loop should be stopping at 5 and when the player or computer reaches this the game should stop.
This is Rock, Paper, Scissors. The result of each game is either player win, computer win or draw.
The game should end once either player reaches 5 wins.
The problem is the game is not ending as intended!
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.");
return prompt("Please choose either 'rock', 'paper', or 'scissors'");
}
function getPlayerMove() {
return getInput();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
}
else if (randomNumber < 0.66) {
return "paper";
}
else {
return "scissors";
}
}
function getComputerMove() {
return randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
// A big limitation of this game is the user is only allowed to choose once! To allow more choices you'd need to design the program differently
function playToFive() {
var playerWins = 0;
var computerWins = 0;
var playerMove = getPlayerMove();
while ((playerWins <= 5) || (computerWins <= 5)) {
var computerMove = getComputerMove();
var winner = getWinner(getPlayerMove, getComputerMove);
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "player") {
playerWins += 1;
}
else if (winner === "computer") {
computerWins += 1;
}
if ((playerWins = 5) || (computerWins = 5)) {
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
playToFive ();
Problem is this line
var winner = getWinner(getPlayerMove, getComputerMove);
you are passing the function reference to the getWinner() method
var winner = getWinner(playerMove , computerMove );
Which means that you need to get moves again later, so change your method to (multiple issues fixed in your code)
function playToFive()
{
var playerWins = 0;
var computerWins = 0;
while ((playerWins <= 5) && (computerWins <= 5)) //this line has && instead of ||
{
var computerMove = getComputerMove();
var playerMove = getPlayerMove(); //this line is now inside while loop
var winner = getWinner( playerMove , computerMove );
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "Player") { //P caps
playerWins += 1;
}
else if (winner === "Computer") { //C caps
computerWins += 1;
}
if ((playerWins == 5) || (computerWins == 5)) { //= is replaced by ==
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
In order for this if to run accordingly:
if ((playerWins = 5) || (computerWins = 5)) {}
You'll need to use the == operator, because just one = is used for value assignation.
if ((playerWins == 5) || (computerWins == 5)) {}
Firstly in the while loop you need to change it too a && statement otherwise if the computer is 8 and the player is 3 the loop will continue until both players are >5.
I Think first you should understand the difference between (==) and (===) here.
Use This Code (Conditional Code not assignment)
if ((playerWins == 5) || (computerWins == 5)) { //use logical Operator not assignment Oprtr.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Instead of ##
if ((playerWins = 5) || (computerWins = 5)) { // Error Code.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Problem is this line
you are passing the function reference to the getWinner() method
use this
var winner = getWinner(playerMove , computerMove );
instead of
var winner = getWinner(getPlayerMove, getComputerMove);
For This Function...
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
Every time this method set tie as winner.
But you should know the difference between (==) equalto and (===) equal value and equal type here
Thanks guys. There were quite a few issues.
Cheers guys. Definitely needed && rather than ||. The || was resulting in the game continuing even
Also var winner = getWinner(getPlayerMove, getComputerMove) was required. This was causing an infinite loop.

Adding user/computer score to a Tweet

Problem: When a user clicks the twitter icon, it brings up a tweet box, but doesn't add the values of the USER_SCORE/COMPUTER_SCORE variables. Right now I have only been testing the USER_SCORE alone.
I figured I could create a text node with the value in it, and append it to the box, however that isn't working, and am unsure on what else would really work.
Desired Result: I want to add the values of the USER_SCORE/COMPUTER_SCORES to the tweet box, when the twitter button is clicked.
JSBIN: http://jsbin.com/gabenafula/edit?html,js,output
JavaScript:
window.onload = function() {
//vars scope may change in the future.
var CHOICE_ROCK = document.querySelector('#rock'),
CHOICE_PAPER = document.querySelector('#paper'),
CHOICE_SCISSORS = document.querySelector('#scissors'),
WINNER_TXT = document.querySelector('#winner'),
BUTTONS = document.querySelectorAll('input'),
COMP_IMG = document.querySelector('#compChoice'),
USER_SCORE_EL = document.querySelector('#user-score'),
COMP_SCORE_EL = document.querySelector('#computer-score'),
PLAYER_CHOICE = document.querySelector('#player-choice'),
TWEET = document.querySelector('#tweet'),
USER_SCORE = 0,
COMPUTER_SCORE = 0,
GAME_SCORE = { USER_SCORE: 0, COMPUTER_SCORE: 0}, // add pt to each per win, stringify to local Storage
key = 'scores';
CHOICE_ROCK.addEventListener('click', USER_CHOICE, false);
CHOICE_PAPER.addEventListener('click', USER_CHOICE, false);
CHOICE_SCISSORS.addEventListener('click', USER_CHOICE, false);
//tweet your score
TWEET.addEventListener('click', function() {
var scoreValue = document.createTextNode(USER_SCORE.value);
window.open('https://twitter.com/intent/tweet?text=').appendChild(scoreValue);
}, false );
// Return user choice value;
function USER_CHOICE(e) {
var compChoice = COMPUTER_CHOICE();
var el = e.target;
if (el === CHOICE_ROCK) {
console.log('USER CHOICE: ROCK');
console.log('COMPS CHOICE: ' + compChoice);
console.log(USER_SCORE);
console.log(COMPUTER_SCORE);
ROCK('rock', compChoice);
PLAYER_CHOICE_STYLE('ROCK!');
USER_SCORE_EL.innerHTML = 'Your Score : ' + USER_SCORE;
COMP_SCORE_EL.innerHTML = 'Computer Score : ' + COMPUTER_SCORE;
} else if (el === CHOICE_PAPER) {
console.log('USER CHOICE: PAPER');
console.log('COMPS CHOICE: ' + compChoice);
console.log(USER_SCORE);
console.log(COMPUTER_SCORE);
PAPER('paper', compChoice);
PLAYER_CHOICE_STYLE('PAPER!');
USER_SCORE_EL.innerHTML = 'Your Score : ' + USER_SCORE;
COMP_SCORE_EL.innerHTML = 'Computer Score : ' + COMPUTER_SCORE;
} else if (el === CHOICE_SCISSORS) {
console.log('USER CHOICE: SCISSORS');
console.log('COMPS CHOICE: ' + compChoice);
console.log(USER_SCORE);
console.log(COMPUTER_SCORE);
SCISSORS('scissors', compChoice);
PLAYER_CHOICE_STYLE('SCISSORS!');
USER_SCORE_EL.innerHTML = 'Your Score : ' + USER_SCORE;
COMP_SCORE_EL.innerHTML = 'Computer Score : ' + COMPUTER_SCORE;
}
e.stopPropagation();
}
// Return value of computer choice
function COMPUTER_CHOICE() {
var num = Math.floor(Math.random() * 3) + 1;
console.log('COMP CHOICE number: ' + num);
if (num === 1) {
COMP_IMG.setAttribute('src', 'http://i.imgur.com/OHt2rjH.png');
COMP_IMG.style.border = '1px solid black';
return 'rock';
} else if (num === 2) {
COMP_IMG.setAttribute('src', 'http://i.imgur.com/H86s3q4.png');
COMP_IMG.style.border = '1px solid black';
return 'paper';
} else if (num === 3) {
COMP_IMG.setAttribute('src', 'http://i.imgur.com/rAkxkWc.png');
COMP_IMG.style.border = '1px solid black';
return 'scissors';
}
}
// Break up into functions
// compare values of user choice and computer chocie
function ROCK(USER_CHOICE, COMPUTER_CHOICE) {
if (USER_CHOICE === CHOICE_ROCK.id && COMPUTER_CHOICE === 'scissors') {
//user wins
USER_SCORE ++;
WINNER_TXT.style.color = 'green';
WINNER_TXT.innerHTML = 'YOU WIN!';
} else if (USER_CHOICE === CHOICE_ROCK.id && COMPUTER_CHOICE === 'paper') {
//comp wins
COMPUTER_SCORE ++;
WINNER_TXT.style.color = 'red';
WINNER_TXT.innerHTML = 'COMPUTER WINS!';
} else if (USER_CHOICE === CHOICE_ROCK.id && COMPUTER_CHOICE === 'rock') {
WINNER_TXT.style.color = 'blue';
WINNER_TXT.innerHTML = 'ITS A TIE!!!!!';
}
}
function PAPER(USER_CHOICE, COMPUTER_CHOICE) {
//Paper
if (USER_CHOICE === CHOICE_PAPER.id && COMPUTER_CHOICE === 'rock') {
//user wins
USER_SCORE ++;
WINNER_TXT.style.color = 'green';
WINNER_TXT.innerHTML = 'YOU WIN!';
} else if (USER_CHOICE === CHOICE_PAPER.id && COMPUTER_CHOICE === 'scissors') {
//comp wins
COMPUTER_SCORE ++;
WINNER_TXT.style.color = 'red';
WINNER_TXT.innerHTML = 'COMPUTER WINS!';
} else if (USER_CHOICE === CHOICE_PAPER.id && COMPUTER_CHOICE === 'paper') {
WINNER_TXT.style.color = 'blue';
WINNER_TXT.innerHTML = 'ITS A TIE!!!!!';
}
}
function SCISSORS(USER_CHOICE, COMPUTER_CHOICE) {
//scissors
if (USER_CHOICE === CHOICE_SCISSORS.id && COMPUTER_CHOICE === 'paper') {
//user wins
USER_SCORE ++;
WINNER_TXT.style.color = 'green';
WINNER_TXT.innerHTML = 'YOU WIN!';
} else if (USER_CHOICE === CHOICE_SCISSORS.id && COMPUTER_CHOICE === 'rock') {
//comp wins
COMPUTER_SCORE ++;
WINNER_TXT.style.color = 'red';
WINNER_TXT.innerHTML = 'COMPUTER WINS!';
} else if (USER_CHOICE === CHOICE_SCISSORS.id && COMPUTER_CHOICE === 'scissors') {
WINNER_TXT.style.color = 'blue';
WINNER_TXT.innerHTML = 'ITS A TIE!!!!!';
}
}
function PLAYER_CHOICE_STYLE(choice) {
PLAYER_CHOICE.innerHTML = 'You chose: ' + choice;
PLAYER_CHOICE.style.fontWeight = 'bold';
PLAYER_CHOICE.style.backgroundColor = '#555';
PLAYER_CHOICE.style.color = 'white';
PLAYER_CHOICE.style.borderBottom = '3px solid #444';
PLAYER_CHOICE.style.borderRadius = '30px';
PLAYER_CHOICE.style.padding ='10px';
}
// Add Local Storage
// function RENDER_SCORES() {
//
// }
//
// //Store scores
// function STORE_SCORE(LOCAL_STORAGE, key) {
// var score = JSON.stringify(LOCAL_STORAGE);
// LOCAL_STORAGE.setItem(key, score);
// }
//fetch scores
// function fetch(key, callback) {
// var LOCAL_STORAGE = JSON.pase(LOCAL_STORAGE.getItem(key));
// callback(LOCAL_STORAGE);
// }
//
// function render(data) {
// if (data !== null && data.hasOwnProperty('forEach')) {
// data.forEach(function(current){
// RENDER_SCORES(current);
// });
// }
// }
};
HTML:
<div class="container">
<div class="header"><h1>ROCK, PAPER, OR SCISSORS!</h1></div>
<div><span id="winner"></span></div>
<div>Computer's choice:</div>
<div><img id="compChoice" src="" alt="computers choice"></div>
<div id="player-choice"></div>
<div class="inner-container">
<div class="row">
<div class='items'>
<img class="rps" id="rock-img" src="https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-027-128.png" width="200" height="300">
<div><input type="submit" value="Rock" id="rock"></div>
</div>
<div class='items'>
<img class="rps" src="https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-019-256.png" width="200" height="300">
<div><input type="submit" value="Paper" id="paper"></div>
</div>
<div class='items'>
<img class="rps" src="https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-014-512.png" width="200" height="300">
<div><input type="submit" value="Scissors" id="scissors"></div>
</div>
</div>
</div>
<div id="scoreboard">
<div><h2 id='user-score'>Your Score:</h2></div>
<div><h2 id='computer-score'>Computer Score:</h2></div>
<img src="https://cdn4.iconfinder.com/data/icons/social-media-icons-the-circle-set/48/twitter_circle-128.png" id="tweet">
</div>
<div class="footer">
<span>© Zack 2016</span>
</div>
</div>
Change the tweet your score section to the following:
//tweet your score
TWEET.addEventListener('click', function() {
var message = "Your score was " + USER_SCORE + ". The computers score was " + COMPUTER_SCORE;
window.open('https://twitter.com/intent/tweet?text=' + message);
}, false );

Categories

Resources