Ties are still running win messages? - javascript

I've been messing around with a rock, paper scissors project that codecademy gets you to try, I'm pretty happy with it but I have one problem! When the result is a tie, it logs the tie message (perfect!) but also logs the win message linked with the result!
How do I get it to ONLY log the tie message?
Here's the code:
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === "rock" || userInput === "paper" || userInput === "scissors" || userInput === "gun") {
return userInput;
} else {
console.log(`Sorry! But ${userInput} is an illegal weapon in the bloodythirsty sport of Rock, Paper, Scissors!`)
}
}
const getComputerChoice = () => {
const ranNum = Math.floor(Math.random() * 3);
switch (ranNum) {
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
}
};
const determineWinner = (getUserChoice, getComputerChoice) => {
if (getComputerChoice === getUserChoice) {
console.log("It seems it's a tie! You've matched wits!");
}
if (getUserChoice === "rock") {
if (getComputerChoice === "paper") {
return "The computer wins! It has gift wrapped your weapon.";
} else {
return "You beat the computer! They immediately begin crafting bigger scissors.";
}
}
if (getUserChoice === "paper") {
if (getComputerChoice === "scissors") {
return "The computer wins! They claim arts and crafts time as a reward."
} else {
return "You beat the computer! Their puny stone was no match for your paper aeroplane to the eye!"
}
}
if (getUserChoice === "scissors") {
if (getComputerChoice === "rock") {
return "The computer wins! You won't be cutting straight lines any time soon..."
} else {
return "You beat the computer! You cause emotional damage by destroying their robot child's drawing. You're a monster."
}
}
if (getUserChoice === "gun") {
if (getComputerChoice === "rock" || getComputerChoice === "paper" || getComputerChoice === "scissors") {
return "You win. But at what cost?"
}
}
if (getUserChoice === undefined) {
return "Come back when you're ready to take this game seriously."
}
}
//Enter your choice below in getUserChoice brackets
const playGame = () => {
let userChoice = getUserChoice("rock");
let computerChoice = getComputerChoice();
if (userChoice !== undefined) {
console.log(`You have chosen ${userChoice} as your weapon.`);
}
if (userChoice !== undefined) {
console.log(`The computer has brought ${computerChoice} to a ${userChoice} fight.`);
}
console.log(determineWinner(userChoice, computerChoice))
}
playGame();

Instead of logging the tie message, you should return it, leaving the logging to the caller:
if (getComputerChoice === getUserChoice) {
return "It seems it's a tie! You've matched wits!";
}

Related

im a new learner and cant figure out why my code is not working

I have just recently got into coding and have chosen to learn JavaScript as my first language. I have written up code for a Rock, Paper, Scissors game but the wrong outputs come out when I run it? for example I would put my answer as scissors and the computer would choose rock and the game will come out as a tie.
const getUserChoice = userInput => {
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
return userInput
} else {
return 'Error!'
}
}
var getComputerChoice = () => {
const randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
case 0:
return 'rock'
break;
case 1:
return 'paper'
break;
case 2:
return 'scissors'
break;
}
};
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return 'its a tie!';
};
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'computer won';
} else {
return 'user won';
}
}
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'computer won';
} else {
return 'user won'
}
}
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'computer won';
} else {
return 'user won'
}
}
};
const playGame = () => {
console.log(`player chose ${getUserChoice('scissors')}`);
console.log(`computer chose ${getComputerChoice()}`);
console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
}
playGame();
Maybe there are more issues, but here are some of them:
Each time you execute getComputerChoice you get a different value because a random value is picked inside:
console.log(`player chose ${getUserChoice('scissors')}`);
console.log(`computer chose ${getComputerChoice()}`);
console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
So you must instead call and store in variables:
let playerChose = getUserChoice('scissors');
let computerChose = getComputerChoice();
let winner = determineWinner(playerChose, computerChose);
console.log(`player chose ${playerChose}`);
console.log(`computer chose ${computerChose}`);
console.log(winner);
You can do it without variables, but be sure not invoking getComputerChoice several times.
Also userInput should be between parenthesis at:
const getUserChoice = (userInput) => {
Every time you call getComputerChoice you'll get a different value, you could save the values in a variable with the const keyword.
const playGame = () => {
// It would be nice if you request this to the user, with prompt
const userChoice = getUserChoice('scissors');
// Save the random value
const computerChoice = getComputerChoice();
console.log(`player chose ${userChoice}`);
console.log(`computer chose ${computerChoice}`);
// This will work
console.log(determineWinner(userChoice, computerChoice));
}
playGame();
More on prompt here

Rock Paper Scissors game returns same result

So I'm having some difficulty with my code (hence the post). I'm trying to make it so where when you click on the picture of the rock, the game begins and it returns the computer's decision. It worked before when I prompted the user but since I've rewritten the logic when I click on the rock, it only returns one answer. Is it because of the lack of loops? I assumed each time I would click on the icon, a different answer would display. I haven't done the code for the other options yet because I figured I would use similar logic for the other options. The only thing I can think of is that because I'm not using a loop, the game basically plays only 1 round.
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
let computerScore = 0;
let playerScore = 0;
function computerPlay() {
var choice = Math.floor(Math.random() * 3 ) + 1; //generate a number 1-3 to find computer choice
if(choice == 1) {
return 'rock';
}
else if(choice == 2) {
return 'paper';
}
else {
return 'scissors'
}
}
// function playGame(computerChoice) {
// // let round = 0
// // while(round < 6) {
// var playerChoice = playerRock || playerPaper || playerScissors;
// var computerChoice = computerPlay();
// if(playerChoice === computerChoice) {
// console.log('Tie!');
// round++;
// }
// else if(playerChoice == 'rock' && computerChoice == 'scissors') {
// playerScore++;
// console.log(`Player chose rock and computer chose scissors! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// round++;
// }
// else if(playerChoice == 'paper' && computerChoice == 'rock') {
// playerScore++;
// round++;
// console.log(`Player chose paper and computer chose rock! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else if(playerChoice == 'scissors' && computerChoice == 'paper') {
// playerScore++;
// round++;
// console.log(`Player chose scissors and computer chose paper! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else {
// computerScore++;
// console.log(`The player chose ${playerChoice} and the computer chose ${computerChoice}! The computer wins! Player: ${playerScore} Computer: ${computerScore}.`)
// }
// // }
// }
// computerPlay()
// playerChoice()
// console.log(playGame())
function playGame(computerChoice) {
computerChoice = computerPlay();
let result;
rock.addEventListener('click', () => {
if(computerChoice == 'rock') {
result = `The computer chose ${computerChoice} and you chose rock! It's a tie!`;
h3.textContent = result;
}
else if(computerChoice == 'paper') {
result = `The computer chose ${computerChoice} and you chose rock! You lose!`;
h3.textContent = result;
computerScore++;
}
else {
result = `The computer chose ${computerChoice} and you chose rock! You win!`;
h3.textContent = result;
playerScore++;
}
});
let playerPaper = paper.addEventListener('click', () => {
return 'paper'
});
let playerScissors = scissors.addEventListener('click', () => {
return 'scissors'
})
}
playGame()
console.log(playGame())
This is what I have so far. Initially, I didn't have a result variable but I thought that might help.
When calling playGame() once, computerChoice is only generated once. Everytime you click on rock paper or scissor it evaluates the players choice, but the computers choice has never changed. If it chooses rock at the beginning it will always compare the users choice to rock.
Either take the eventListeners out of the playGame function and call playGame after the result is shown (Recursive-style loop)
Or, after the result is shown reset computerChoice to the result of another computerPlay() call. You can add computerChoice = computerPlay() to the end of your event listener function after the else statement to run regardless of the outcome.
You need to do some changes ...
1- add event at first time
add useChoicevariable
and show reult of game on click
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
let computerScore = 0;
let playerScore = 0;
let computerChoice = "";
let userChoice = "";
rock.addEventListener('click', () => {
userChoice = "rock";
ShowResult()
});
paper.addEventListener('click', () => {
userChoice = 'paper';
ShowResult()
});
scissors.addEventListener('click', () => {
userChoice = 'scissors';
ShowResult()
})
function computerPlay() {
var choice = Math.floor(Math.random() * 3) + 1; //generate a number 1-3 to find computer choice
if (choice == 1) {
return 'rock';
}
else if (choice == 2) {
return 'paper';
}
else {
return 'scissors'
}
}
// function playGame(computerChoice) {
// // let round = 0
// // while(round < 6) {
// var playerChoice = playerRock || playerPaper || playerScissors;
// var computerChoice = computerPlay();
// if(playerChoice === computerChoice) {
// console.log('Tie!');
// round++;
// }
// else if(playerChoice == 'rock' && computerChoice == 'scissors') {
// playerScore++;
// console.log(`Player chose rock and computer chose scissors! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// round++;
// }
// else if(playerChoice == 'paper' && computerChoice == 'rock') {
// playerScore++;
// round++;
// console.log(`Player chose paper and computer chose rock! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else if(playerChoice == 'scissors' && computerChoice == 'paper') {
// playerScore++;
// round++;
// console.log(`Player chose scissors and computer chose paper! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else {
// computerScore++;
// console.log(`The player chose ${playerChoice} and the computer chose ${computerChoice}! The computer wins! Player: ${playerScore} Computer: ${computerScore}.`)
// }
// // }
// }
// computerPlay()
// playerChoice()
// console.log(playGame())
function ShowResult() {
if (computerChoice == userChoice) {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! It's a tie!`;
h3.textContent = result;
} else if (
computerChoice == 'paper' && userChoice == "rock"
|| computerChoice == 'scissors' && userChoice == "paper"
|| computerChoice == 'rock' && userChoice == "scissors"
) {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! You lose!`;
h3.textContent = result;
computerScore++;
} else {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! You win!`;
playerScore++;
h3.textContent = result + playerScore ;
}
playGame()
}
function playGame() {
computerChoice = computerPlay();
console.log( "Computer Choice:" + computerChoice);
}
playGame()
<div class="rock">rock</div>
<div class="paper">paper</div>
<div class="scissors">scissors</div>
<h3></h3>

Tie result cannot be outputted

While creating the rock, paper, scissors application, I am tasked to output specific results in the console, such as outputting paper-paper and receive 'It's a tie' result. Well, I have tried to do that but for some reason, I cannot do so. The code is as below:
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
const winner = () => {
const choice1 = user('rock');
const choice2 = computer();
if(choice1 === choice2) {
return 'It\'s a tie!';
}
if(choice1 === 'rock') {
if(choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'paper') {
if(choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'scissors') {
if(choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
}
console.log(winner('paper', 'paper'));
When I try to type console.log(winner('paper', 'paper')) for example, the result is random meaning that it can be either win, lost or tie due to the fact (or what I suppose is the reason) that the computer's choice is random but this is how I am asked to create the computer's choice. If I type console.log(('paper', 1)) I get the same result but somehow, the task is asking me to use console.log(winner('paper', 'paper')) and is telling me that the result should be a tie. I have also tried to let the user with no parameter in choice1 but I get an error due to the fact that there is no input in the user's choice.
The tasks are as below:
console.log(determineWinner('paper', 'scissors')); // prints something like 'The computer won!'
console.log(determineWinner('paper', 'paper')); // prints something like 'The game is a tie!'
console.log(determineWinner('paper', 'rock')); // prints something like 'The user won!'
Any help or idea would be appreciated. Thanks!
Something like this would work. If It is what you need.
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
const random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
// Here is where you need to change something
const determineWinner = (userChoice, computerChoice) => {
// And use the parameters here:
const choice1 = userChoice;
const choice2 = computerChoice;
if (choice1 === choice2) {
return 'It\'s a tie!';
}
if (choice1 === 'rock') {
if (choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'paper') {
if (choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'scissors') {
if (choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
};
const userInput = 'rock';
console.log(determineWinner(user(userInput), computer()));
console.log(determineWinner('rock', 'paper'));
console.log(determineWinner('paper', 'paper'));
// For you requirement:
console.log(determineWinner('paper', 'scissors'));
console.log(determineWinner('paper', 'paper'));
console.log(determineWinner('paper', 'rock'));
But if you hardcode the parameters as you requirement suggests then your functions user and computer are not used.

ReferenceError: prompt is not defined - Rock, Paper, or Scissors

I am experiencing some issues to finish this code.
ReferenceError: prompt is not defined
at Object. //(/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:1:80) this is the first error, I tried not to use prompt, and just calling the code at the end, but I need some advice on what is the best practice for that.
Could someone give tips to improve this code?
let userPrompt = prompt("enter a choice: ");
const getUserChoice = userPrompt => {
if (userInput === 'rock' || userInput === 'Paper' || userInput === 'scissors') {
return userInput;
} else {
console.log('Error');
}
}
const randomNumber = 'Math.floor(Math.random() * 3)';
switch (randomNumber) {
case 0:
return 'rock';
// I don't know if I have to have a break here.
case 1:
return 'Paper';
case 2:
return 'scissors';
case 3:
return 'bomb';
}
console.log(getUserChoice());
function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return 'the game is a tie';
}
if (userChoice === 'bomb') {
return 'You won!'; /* add a fourth condition that checks if the userInput is 'bomb'.At the beginning of determineWinner(), add another if statement that makes the user win if the userChoice is 'bomb'.*/
}
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'The computer won!';
} else {
return 'You won!';
}
} else if (userChoice === 'Paper') {
if (computerChoice === 'rock') {
return 'The user won';
} else {
return 'The computer won';
}
} else if (userChoice === 'Scissors') {
if (computerChoice === 'Paper') {
return 'The user won';
} else {
return 'The computer won';
}
}
}
console.log(determineWiner('rock', 'paper'));
console.log(determineWiner('paper', 'rock'));
console.log(determineWiner('scissors', 'paper'));
const playGame = () => {
const userChoice =
getUserChoice('scissors');
const computerChoice =
getComputerChoice();
console.log(`you threw: ${userChoice}`);
console.log(`The computer threw: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
};
playgame();

Javascript not running - no error message

I've set up this rock, paper scissors game. However, the Javascript is not running and I'm not receiving any errors. Any suggestions?
function play(humanScore) {
var computerScore = getcomputerScore();
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
human++
} else if (computerScore == "paper") {
computer++
}
} else if (humanScore == "scissors") {
if (computerScore == "scissors") {
} else if (computerScore == "paper") {
human++
} else if (computerScore == "rock") {
computer++
}
} else if (humanScore == "paper") {
if (computerScore == "paper") {
} else if (computerScore == "scissors") {
computer++
} else if (computerScore == "rock") {
human++
}
}
}
function getcomputerScore() {
var randomplay = ["rock", "paper", "scissors"];
var play = randomplay[Math.floor(Math.random() * myArray.length)];
return play
}
This is the code setting up humanScore:
var human = 0;
var computer = 0;
document.getElementById("rock").onClick = pickRock;
document.getElementById("scissors").onClick = pickScissors;
document.getElementById("paper").onClick = pickPaper;
function pickRock() {
play("rock");
}
function pickScissors() {
play("scissors");
}
function pickPaper() {
play("paper");
}
The name of the property is onclick, not onClick; note the lowercase c.
There’s at least one other error (myArray.length, as #RobG points out), but this will make them actually throw.
Probably better suited to a code review section, but here goes…
function play(humanScore) {
var computerScore = getcomputerScore();
variables humanScore and computerScore aren't actually scores, they are symbols the players have chosen to play, so the variables might be better as humanChoice and computerChoice. This also means that the globals human and computer can be better named as humanScore and computerScore.
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
Rather than leaving a blank block, better to either insert a comment to say "no adjustment". Better to test equivalent choices up front, then you're left with binary choices, so you can do something like:
var humanScore = 0;
var computerScore = 0;
function play(humanChoice) {
// IE tends to play with capitalisation of values
humanChoice = humanChoice.toLowerCase();
var computerChoice = getComputerChoice();
// If same choice, no change of score
if (computerChoice == humanChoice) {
return;
}
// Only binary win/lose choices left
if (humanChoice == 'rock') {
computerChoice == 'paper'? ++computerScore : ++humanScore;
} else if (humanChoice == 'paper') {
computerChoice == 'scissors'? ++computerScore : ++humanScore;
} else if (humanChoice == 'scissors') {
computerChoice == 'rock'? ++computerScore : ++humanScore;
}
}
There was an error in this function too:
function getComputerChoice() {
var choices = ['rock','paper','scissors'];
return choices[Math.random()*choices.length | 0];
}
Lastly, make sure the buttons are in the page before adding the listener, and make sure the property names have the correct case (it doesn't matter for HTML attributes, but it does for javascript property names):
window.onload = function() {
document.getElementById("rock").onclick = pickRock;
document.getElementById("scissors").onclick = pickScissors;
document.getElementById("paper").onclick = pickPaper;
}

Categories

Resources