JavaScript - Rock Paper Scissors in console - javascript

I'm having problems getting my simple Rock Paper Scissors game to display the winner of each game when the user chooses anything either than Rock. How do I use multiple if...else statements so that my declareWinner function works when the user chooses Scissors or Paper?
let choices = ["rock", "paper", "scissors"];
// GETTING USER INPUT
const userInput = prompt("Do you choose rock, paper or scissors?").toLocaleLowerCase();
if(userInput ==="paper" || userInput ==="rock" || userInput ==="scissors"){
console.log("You chose " + `${userInput}`);
} else {
console.log("Error! Try again!");
}
// GETTING COMPUTER INPUT
const computerInput = choices[Math.floor(Math.random() * 3)];
console.log("Computer chose" + ` ${computerInput}`);
if (computerInput <= 0.33) {
computerInput = "rock";
}
if (computerInput >= 0.67) {
computerInput = "paper";
}
if (computerInput >= 0.66) {
computerInput = "scissors";
}
// DECLARE WINNER
// User Chooses Rock
function declareWinner(userInput, computerInput) {
if(userInput === "rock" && computerInput === 'paper') {
console.log ('You win! Rock beats paper!');
} else if (userInput === 'rock' && computerInput === 'rock') {
console.log ('Its a tie!');
} else if (userInput === 'rock' && computerInput === 'scissors') {
console.log ('You win! Rock beats scissors!');
// User Chooses Paper
} else if(userInput === "paper" && computerInput === 'rock') {
console.log ('You win! Rock beats paper!');
} else if (userInput === 'paper' && computerInput === 'paper') {
console.log ('Its a tie!');
} else if (userInput === 'paper' && computerInput === 'scissors') {
console.log ('You lose! Scissors beats paper!');
// User Chooses Scissors
} else if(userInput === "scissors" && computerInput === 'rock') {
console.log ('You lose! Rock beats scissors!');
} else if (userInput === 'scissors' && computerInput === 'paper') {
console.log ('You win! Scissors beats paper!');
} else {
console.log ('It is a tie!');
}
}
declareWinner();

There were two problems with the code:-
You are doing choices[Math.floor(Math.random() * 3)]; which results in a random value from choices array, so there is no need for multiple if-else statements that were after it.
You were missing the declareWinner function declaration.
Also, You are missing some conditions in declareWinner function, like userInput === 'paper' && computerInput === 'rock', userInput === 'rock' && computerInput === 'scissors' etc.
const choices = ["rock", "paper", "scissors"];
// GETTING USER INPUT
const userInput = prompt("Do you choose rock, paper or scissors?");
if (userInput === "paper" || userInput === "rock" || userInput === "scissors") {
console.log("You chose " + `${userInput}`);
} else {
console.log("Error! Try again!");
}
// GETTING COMPUTER INPUT
let computerInput = choices[Math.floor(Math.random()*3)];
console.log("Computer chose" + ` ${computerInput}`);
// DECLARE WINNER
const winner = declareWinner(userInput, computerInput);
function declareWinner(userInput, computerInput) {
if (userInput === 'rock' && computerInput === 'paper') {
console.log('You lose! Rock beats Paper');
} else if (userInput === 'scissors' && computerInput === 'paper') {
console.log('You win! Scissors beats Paper');
} else {
console.log('You tie!');
}
}
Tip:- You can use an object to choose the winner in declareWinner function.
const choices = ["rock", "paper", "scissors"];
// GETTING USER INPUT
const userInput = prompt("Do you choose rock, paper or scissors?");
if (userInput === "paper" || userInput === "rock" || userInput === "scissors") {
console.log("You chose " + `${userInput}`);
} else {
console.log("Error! Try again!");
}
// GETTING COMPUTER INPUT
let computerInput = choices[Math.floor(Math.random() * 3)];
console.log("Computer chose" + ` ${computerInput}`);
// DECLARE WINNER
const winner = declareWinner(userInput, computerInput);
function declareWinner(userInput, computerInput) {
let win = {
rock: "scissors",
paper: "rock",
scissors: "paper"
};
if (win[userInput] === computerInput) {
console.log(`You won! ${userInput} beats ${computerInput}`);
} else if (win[computerInput] === userInput) {
console.log(`You lost! ${computerInput} beats ${userInput}`);
} else console.log("Tie")
}

You can't change a const value. Use let instead:
let computerInput = choices[Math.floor(Math.random() * 3)];

Related

stuck on the if on Rock, paper, scissors

I am new to coding I have to do this rock paper scissors but can't find my error it still show me the else result each time.
Any help are welcome
// Get the computer choice
function getComputerChoice() {
"use strict";
const computerPlay = Math.floor(Math.random()*3);
if (computerPlay === 1){
return("rock")
}
else if(computerPlay === 2){
return ("paper")
}
else {
return ("scissors")
}
}
// Get the user choice
function getUserChoice(){
prompt("Please enter 'rock', 'paper', 'scissors': ").toLowerCase();
}
// Play a round
function playRound(){
let computerSelection = getComputerChoice();
let playerSelection = getUserChoice();
if (computerSelection === playerSelection){
console.log("Game is a Tie")
}
else if (computerSelection == 'paper' && playerSelection == 'rock'){
console.log("Computer Win")
}
else if (computerSelection == 'rock' && playerSelection == 'scissors'){
console.log("Computer Win")
}
else if (computerSelection == 'scissors' && playerSelection == 'paper'){
console.log("Computer Win")
}
else {
console.log("User Win")
}
}
// Play Game function
function playGame(){
for (let i = 0; i < 5; i++){
playRound()
}
}
playGame()
I try the if seems it miss something to run correctly.
Solution
You've missed the return keyword from the getUserChoice method.
function getUserChoice(){
return prompt("Please enter 'rock', 'paper', 'scissors': ").toLowerCase();
}

Scoreboard and determine winner Rock Paper Scissors (JavaScript)

I'm working on Rock Paper Scissors and I'm lost at how to keep and display scores as well as determine a winner when they reach a score of 5. Right now, I'm adding +1 to the playerScore or compScore depending on the single round result, but I don't know how to display or keep track of it. Here is my code so far. Any tips are greatly appreciated!
//choices array
const choices = ["rock", "paper", "scissors"];
//set scores to 0
let playerScore = 0;
let compScore = 0;
//Get random choice from comp
function getComputerChoice() {
const randomNum = Math.floor(Math.random() * 3) //Generate random num with Math.random(), to ensure it's between 0 and 3, multiply by 3. Use Math.floor to round to down to nearest num
switch (randomNum) { //Create switch statement to take randomNum variable to perform different action based on the condition (case)
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
}
}
//single round gameplay
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == "scissors") {
//Add 1 to playerScore
playerScore+= 1
return "You win! Rock beats scissors";
} else if (playerSelection == "rock" && computerSelection == "paper") {
//Add 1 to compScore
compScore+= 1
return "You lose. Paper beats rock";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore+= 1
return "You win! Scissors beat paper";
} else if (playerSelection == "scissors" && computerSelection == "rock") {
compScore+= 1
return "You lose. Rock beats scissors";
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore+= 1
return "You win! Paper beats rock";
} else if (playerSelection == "paper" && computerSelection == "scissors") {
compScore+= 1
return "You lose. Scissors beat paper";
} else if (playerSelection === computerSelection) {
return "It's a tie";
} else {
return "Try again";
}
}
function userInput() {
let ask = false;
//while ask is still false, continue looping
while (ask == false){
const selction = prompt("Rock Paper or Scissors?")
// if the prompt return is empty
if (selction == null){
//keep looping
continue;
}
const selctionLower = selction.toLowerCase();
//ask if array of choices [rock, paper, scissors] is in the user input
if (choices.includes(selctionLower)){
//then ask is true
ask = true;
return selctionLower;
}
}
}
function game() {
//loop
for (let i = 0; i < 5; i++) {
const playerSelection = userInput();
const computerSelection = getComputerChoice();
//call playRound function
console.log(playRound(playerSelection, computerSelection));
}
}
game()

Conditional console.log message always displays itself

I am trying to create a simple rock, paper, scissors game to be played in the console. I am attempting to create an "invalid" message when a player inputs anything other than "rock," "paper," or "scissors."
Here is the if statement that I have devised:
if (playerSelection !== "rock", "paper", "scissors") {
console.log("Invalid")
This code displays the console.log message in all cases. I can't figure out what the problem is here.
Here is the whole code:
//create variable for each object
const getComputerChoice = ["rock", "paper", "scissors"]
//select one variable randomly
const computerSelection = Math.floor(Math.random() *
getComputerChoice.length);
//create prompt
const playerSelection = prompt("Rock, Paper, or
Scissors?").toLowerCase();
//player selection is rock
if (playerSelection === "rock" && getComputerChoice[computerSelection]
=== "rock") {
console.log("It's a tie!")
} else if (playerSelection === "rock" &&
getComputerChoice[computerSelection] === "paper") {
console.log("You lose! Paper beats rock")
} else if (playerSelection === "rock" &&
getComputerChoice[computerSelection] === "scissors") {
console.log("You win! Rock beats scissors")
}
//player selection is paper
if (playerSelection === "paper" && getComputerChoice[computerSelection]
=== "rock") {
console.log("You win! Paper beats rock")
} else if (playerSelection === "paper" &&
getComputerChoice[computerSelection] === "paper") {
console.log("It's a tie!")
} else if (playerSelection === "paper" &&
getComputerChoice[computerSelection] === "scissors") {
console.log("You lose! Scissors beats paper")
}
//player selection is scissors
if (playerSelection === "scissors" &&
getComputerChoice[computerSelection] === "rock") {
console.log("You lose! Rock beats scissors")
} else if (playerSelection === "scissors" &&
getComputerChoice[computerSelection] === "paper") {
console.log("You win! Scissors beats paper")
} else if (playerSelection === "scissors" &&
getComputerChoice[computerSelection] === "scissors") {
console.log("It's a tie!")
}
//player inputs invalid term
if (playerSelection !== "rock", "paper", "scissors") {
console.log("Invalid")
}
Your if condition is incorrect.
There are multiple solutions:
Use includes():
let playerSelection = "rock";
if (!["rock", "paper", "scissors"].includes(playerSelection)) {
console.log("Invalid")
} else {
console.log("Valid")
}
Use NOT (!) and logical OR (||).
let playerSelection = "rock";
const isValidChoice = playerSelection === "rock" ||
playerSelection === "paper" ||
playerSelection === "scissors";
if (!isValidChoice) {
console.log("Invalid")
} else {
console.log("Valid")
}
Use a Set. Please note: This is less performant for the three items in the array here, but if you have many items to compare to this will be the fastest option as lookups are performed in O(1) instead of O(n) (as is the case for includes()).
let playerSelection = "rock";
// create set once, then only use for lookups
const possibleChoices = new Set(["rock", "paper", "scissors"]);
if (!possibleChoices.has(playerSelection)) {
console.log("Invalid")
} else {
console.log("Valid")
}
The "inversion" according to De Morgan's laws will of course also work.

Rock,Paper,Scissors round counter in JavaScript

I'm trying to make a console version of rock paper scissors. The game is working for now but I can't run the for loop, what I want to do is at the end of each round, the console will say what round we are in and tell who won the current round. It will be the Best of 5 and the winner will be determined in round 5.
Since I'm a beginner I couldn't try too much. I know my code is not clean and complicated because I proceed by trying and I'm also new to Stackoverflow, if there is something missing in the topic, I apologize in advance for those.
// PLAYER CODES
let playerSelection = prompt('Do you choose Rock, Paper or Scissors?')
if (playerSelection === 'Rock' || playerSelection === 'Paper' || playerSelection === 'Scissors') {
console.log("You chose " + `${playerSelection}`);
} else {
console.log('Error! Pick Rock, Paper or Scissors')
}
// COMPUTER CODES
let computerSelection = getComputerChoice();
function getComputerChoice() {
let choices = ['Rock', 'Paper', 'Scissors'];
let random = choices[Math.floor(Math.random() * 3)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
return ('Draw')
} else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) {
return ('Player Wins! Rock beats Scissors.')
} else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) {
return ('Player Wins! Scissors beats Paper.')
} else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) {
return ('Player Wins! Paper beats Rock.')
} else if ((computerSelection === 'Scissors') && (playerSelection === 'Paper')) {
return ('Computer Wins! Scissors beats Paper.')
} else if ((computerSelection === 'Paper') && (playerSelection === 'Rock')) {
return ('Computer Wins! Paper beats Rock.')
} else if ((computerSelection === 'Rock') && (playerSelection === 'Scissors')) {
return ('Computer Wins! Rock beats Scissors.')
}
}
function game() {
for (let i = 1; i < 6; i++){
playRound(playerSelection, computerSelection);
if (i == 1)
return ('Round 1')
else if (i == 2)
return ('Round 2')
else if (i == 3)
return ('Round 3')
else if (i == 4)
return ('Round 4')
else if (i == 5)
return ('Round 5')
}
}
console.log("Computer chose " + `${computerSelection}`);
console.log(playRound(playerSelection, computerSelection));
console.log(game(playRound));
You have to put the sections to get the player and computer choices inside the loop. I fixed some other problems, too.
// PLAYER CODES
function getPlayerChoice () {
let playerSelection = prompt('Do you choose Rock, Paper or Scissors?')
if (playerSelection === 'Rock' || playerSelection === 'Paper' || playerSelection === 'Scissors') {
console.log("You chose " + `${playerSelection}`);
return playerSelection
} else {
console.log('Error! Pick Rock, Paper or Scissors')
return getPlayerChoice()
}
}
// COMPUTER CODES
function getComputerChoice() {
let choices = ['Rock', 'Paper', 'Scissors'];
let random = choices[Math.floor(Math.random() * 3)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
return ('Draw')
} else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) {
return ('Player Wins! Rock beats Scissors.')
} else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) {
return ('Player Wins! Scissors beats Paper.')
} else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) {
return ('Player Wins! Paper beats Rock.')
} else if ((computerSelection === 'Scissors') && (playerSelection === 'Paper')) {
return ('Computer Wins! Scissors beats Paper.')
} else if ((computerSelection === 'Paper') && (playerSelection === 'Rock')) {
return ('Computer Wins! Paper beats Rock.')
} else if ((computerSelection === 'Rock') && (playerSelection === 'Scissors')) {
return ('Computer Wins! Rock beats Scissors.')
}
}
function game() {
for (let i = 1; i < 6; i++){
console.log('Round ' + i)
let playerSelection = getPlayerChoice();
let computerSelection = getComputerChoice();
console.log("Computer chose " + `${computerSelection}`);
console.log(playRound(playerSelection, computerSelection));
}
}
game()

Javascript output in alert is different in console, and counter is not working properly even when condition is met

I'm making a rock paper scissors games where the counter should add 1 if user wins, add 0.5 if it's a tie, and remains the same if user lost. But in the alert and what's shown in the console doesn't match. Sometimes its shown in the alert that I win and in the console its shown I lose or its a tie. And the counter doesn't add up correctly.
In the image above it's shown 3 wins, 1 tie, and 1 lose. It should show I've won 3.5 games but it shows 5.5. And there is only 5 games played so it should be impossible to win 5.5.
Here is the code:
let winCounter = 0;
// playRound function will play a game of rock, paper, scissors and returns the result
function playRound(playerSelection, computerSelection) {
let getPlayerInsensitive = playerSelection.toLowerCase();
if (getPlayerInsensitive === "rock" && computerSelection === "Rock") {
winCounter+=0.5;
return "It's a tie, both are Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Paper") {
winCounter = winCounter;
return "You Lose! Paper beats Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Scissors") {
winCounter+=1;
return "You win! Rock beats Scissors";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Rock") {
winCounter+=1;
return "You win! Paper beats Rock";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Paper") {
winCounter+=0.5;
return "It's a tie! Both are Paper";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Scissors") {
winCounter = winCounter;
return "You lose! Scissors beats Paper";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Rock") {
winCounter = winCounter;
return "You lose! Rock beats Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Paper") {
winCounter+=1;
return "You win! Scissors beat Paper";
} else {
return "Check your spelling!";
}
}
// game function returns the winner after five rounds
function game() {
for (let i = 0; i < 5; i++) {
let getSelect = prompt("Choose Rock, Paper, or Scissors", "");
if (getSelect === null || getSelect === "") {
alert("You clicked Cancel!");
}
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
//outputs the winner of 5 games
if (i === 4) {
alert("You've played 5 games");
if (winCounter >= 3) {
alert(`You've won ${winCounter} out of 5 games. You win!`);
return `You've won ${winCounter} out of 5 games. You win!`;
} else if (winCounter === 2.5) {
alert(`You've won 2.5 out of 5 games. It's a tie!`);
return `You've won 2.5 out of 5 games. It's a tie!`;
} else if (winCounter < 2.5) {
alert(`You've won ${winCounter} out of 5 games. You lost!`);
return `You've won ${winCounter} out of 5 games. You lost!`;
}
}
}
}
console.log(game());
And here is the fiddle: https://jsfiddle.net/JaredDev/o62hr7as/125/
Why does it show different results in alert and console.log
It's because you called the computerPlay function twice, thus could returns different selection each time it is called,
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
you could change it to this, so it is called only once
const result = playRound(getSelect, computerPlay())
alert(result);
if (i < 5) {
console.log(result)
}
also why the score could be more than it should have, its because playRound function also called twice each turn
Caling code with random behaviour and side-effects twice
This piece of code produces an unintended result because the function computerPlay has random behaviour and the function playRound has has side-effects (modifies the winCounter).
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
You could correct this part of the problem by calling the function only once and assigning its result to a variable:
const result = playRound(getSelect, computerPlay());
alert(result);
if (i < 5) {
console.log(result);
}
Typo
You also have a typo:
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
This should say += not just =:
winCounter+=0.5;

Categories