Javascript (Rock Paper Scissors) / only can return the "else" value - javascript

I am a beginner of javascript learner. Still can't grasp the function concept so far :-(.
Now trying to code this game.
Since It only return the "else" value (Tie), Is anyone can tell what's the main problem in my code? (I know there's a lot of problem:-()
function getComputerChoice () {
const myArray=["Rock" , "Paper", "Scissors"]
const random = Math.floor(Math.random() * myArray.length);
console.log(random, myArray[random]);
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === "Rock" && computerSelection === "Paper") {
return("You Lose! Paper beats Rock");
} else if (playerSelection === 'Paper' && computerSelection === "Scissors") {
return("You Lose! Scissors beats Paper");
} else if (playerSelection === "Scissors" && computerSelection === "Rock") {
return("You Lose! Rock beats Scissors");
} else if (playerSelection === "Rock" && computerSelection === "Scissors") {
return("You Win! Rock beats Scissors");
} else if (playerSelection === "Paper" && computerSelection === "Rock") {
return("You Win! Paper beats Rock");
} else if (playerSelection === "Scissors" && computerSelection === "Paper") {
return("You Win! Scissors beats Paper");
} else {
return("It's tie")
}
}
const playerSelection = "rock";
const computerSelection = getComputerChoice();
function game() {
for (let i = 0; i < 5; i++) {
var result = playRound.call(this, playerSelection, computerSelection)
console.log(result)
}
}
game()
enter image description here

You are not returning any data in your getComputerChoice function,
computerSelection variable is undefined.
function getComputerChoice () {
const myArray=["Rock" , "Paper", "Scissors"]
const random = Math.floor(Math.random() * myArray.length);
return myArray[random]
}
and notice your playerSelection variable, it's lowercase
const playerSelection = "rock"; // should be "Rock"

As noted in other answers, your playerSelection value is a lowercase string i.e. not equal to it's capitalized form.
Though that can just be fixed by changing "rock" to "Rock" in the declaration of your constant, this type of issue is the reason why constants exist in programming (among other reasons).
Best Practice with Magic Strings
Notice that you have "Rock", "Paper" and "Scissors" written many times throughout your code. These are called magic strings:
Magic strings are string values that are specified directly within application code that have an impact on the application's behavior.
It's a good practice to store your magic strings inside constants, and then reference those constants throughout your code. This habit will save you the headache of having unnoticed human typos in your magic strings.
Here's what your code would look like having all the magic strings stored in constants (declared once):
const ROCK = "rock";
const PAPER = "paper";
const SCISSORS = "scissors";
// Declare choices array outside a function scope
// so it's only declared once
const CHOICES = [ROCK, PAPER, SCISSORS]
function getComputerChoice () {
const random = Math.floor(Math.random() * CHOICES.length);
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === ROCK && computerSelection === PAPER) {
return("You Lose! Paper beats Rock");
} else if (playerSelection === PAPER && computerSelection === SCISSORS) {
return("You Lose! Scissors beats Paper");
} else if (playerSelection === SCISSORS && computerSelection === ROCK) {
return("You Lose! Rock beats Scissors");
} else if (playerSelection === ROCK && computerSelection === SCISSORS) {
return("You Win! Rock beats Scissors");
} else if (playerSelection === PAPER && computerSelection === ROCK) {
return("You Win! Paper beats Rock");
} else if (playerSelection === SCISSORS && computerSelection === PAPER) {
return("You Win! Scissors beats Paper");
} else {
return("It's tie")
}
}
// if the player has to write down their choice, transform it with String.toLowerCase()
const playerSelection = ROCK;
const computerSelection = getComputerChoice();
function game() {
for (let i = 0; i < 5; i++) {
var result = playRound.call(this, playerSelection, computerSelection)
console.log(result)
}
}
game()
I hope you find this tip helpful in the future! :)

In the game() section you are passing three parameters in playRound() when the function is defined with only two. Try this:
var result = playRound(playerSelection, computerSelection);
Also, change all your triple quotes to doubles.
I'm sure others will find more suggestions, I'm only learning too so I hope this is actually helpful.

Related

Rock-Paper-Scissors computerSelection not updating in loop Javascript

I am writing this simple console game Rock-Paper-Scissors for TheOdinProject course
I'm having a problem with with the computerSelection not being updated in loop.
There should be 5 rounds in which a player enters rock/paper/scissors in the prompt window and it gets compared against randomized computer answer.
The overall logic of the game seems to be working fine but the problem is that computerSelection stays the same every turn once generated in round 1 but the prompt updates playerSelection as it should.
Here's the code:
const rock = 'rock';
const paper = 'paper';
const scissors = 'scissors';
let playerSelection = '';
const computerSelection = getComputerChoice();
function getComputerChoice() {
let items = [rock, paper, scissors];
let random = Math.floor(Math.random() * 3);
let choice = items[random];
return choice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == computerSelection) {
roundResult = "It's a Draw";
} else if (playerSelection == rock && computerSelection == paper) {
roundResult = "Computer wins this round! Paper beats rock!";
} else if (playerSelection == rock && computerSelection == scissors) {
roundResult = "Human wins this round! Rock beats scissors!";
} else if (playerSelection == paper && computerSelection == rock) {
roundResult = "Human wins this round! Paper beats rock!"
} else if (playerSelection == paper && computerSelection == scissors) {
roundResult = "Computer wins this round! Scissors beats paper";
} else if (playerSelection == scissors && computerSelection == rock) {
roundResult = "Computer wins this round! Rock beats scissors!";
} else if (playerSelection == scissors && computerSelection == paper) {
roundResult = "Human wins this round! Scissors beats paper!";
}
return roundResult;
}
function game() {
for (let i = 0; i < 5; i++) {
playRound(prompt("What do you choose?"), computerSelection);
console.log(roundResult);
}
}
onsole.log("Machine: " + computerSelection);
console.log(game());
as #Barmar suggested, all I had to do was put the
const computerSelection = getComputerChoice();
inside the loop.
const rock = 'rock';
const paper = 'paper';
const scissors = 'scissors';
let playerSelection = '';
const computerSelection = getComputerChoice();
function getComputerChoice() {
let items = [rock, paper, scissors];
let random = Math.floor(Math.random() * 3);
let choice = items[random];
return choice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == computerSelection) {
roundResult = "It's a Draw";
} else if (playerSelection == rock && computerSelection == paper) {
roundResult = "Computer wins this round! Paper beats rock!";
} else if (playerSelection == rock && computerSelection == scissors) {
roundResult = "Human wins this round! Rock beats scissors!";
} else if (playerSelection == paper && computerSelection == rock) {
roundResult = "Human wins this round! Paper beats rock!"
} else if (playerSelection == paper && computerSelection == scissors) {
roundResult = "Computer wins this round! Scissors beats paper";
} else if (playerSelection == scissors && computerSelection == rock) {
roundResult = "Computer wins this round! Rock beats scissors!";
} else if (playerSelection == scissors && computerSelection == paper) {
roundResult = "Human wins this round! Scissors beats paper!";
}
return roundResult;
}
function game() {
for (let i = 0; i < 5; i++) {
const computerSelection = getComputerChoice();
playRound(prompt("What do you choose?"), computerSelection);
console.log(roundResult);
}
}
console.log("Machine: " + computerSelection);
game();
Pass the getComputerChoice() in the playground args.
playRound(prompt("What do you choose?"), getComputerChoice());

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.

The odin project rock, paper, scissor always a tie

I have been trying to complete the odin projects console-based rock, paper, scissors game and I think I have most of it done. For some reason however, the result of the game is always a tie and I cannot figure out what the problem is. Furthermore, the program runs once before going on the loop for five rounds. I would appreciate if anyone could offer some advice as to what I'm doing wrong.
Here's the code:
let choices = ["rock", "paper", "scissors"]
let userScore = 0;
let computerScore = 0;
let playerSelection = playerPlay();
let computerSelection = computerPlay();
function playerPlay(){
//player input
let playerChoice = prompt("Please type either 'rock', 'paper' or 'scissors' to play: ").toLowerCase();
return playerChoice;
}
function computerPlay(){
//computer chooses one of the three choices at random
let random = choices[Math.floor(Math.random() * choices.length)];
return random;
}
function playRound(playerSelection, computerSelection) {
//one round of the game
computerPlay();
playerPlay();
if (playerSelection === computerSelection) {
return("It is a tie!");
}
else if (computerSelection === "rock" && playerSelection === "paper") {
userScore++;
return("You win! Paper beats rock");
}
else if (computerSelection === "scissors" && playerSelection === "rock") {
userScore++;
return("You win! Rock beats scissors");
}
else if (computerSelection === "paper" && playerSelection === "scissors") {
userScore++;
return("You win! Scissors beats paper");
}
else if (computerSelection === "rock" && playerSelection === "scissors") {
computerScore++;
return("You lose! Rock beats scissors");
}
else if (computerSelection === "paper" && playerSelection === "rock") {
computerScore++;
return("You lose! Paper beats rock");
}
else if (computerSelection === "scissors" && playerSelection === "paper") {
computerScore++;
return("You lose! Scissors beats paper");
}
}
function game(){
//play the game for five rounds
for (let i = 0; i < 5; i++) {
playRound();
console.log(`You ${userScore} vs. ${computerScore} Computer`);
}
}
game();

(Javascript) Rock, scissors, paper. The random function is not working as expected [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
It's my first time posting on this website.
At the moment I'm trying to build the rock, scissors, paper game on Javascript. I've already written out the code, however I have a problem running the code.
Whenever I refresh the browser to play the game, the console.log at the bottom will run the game but the computerPlay() will always be scissors. I've tried running computerPlay() on it's own which works properly.
Any help would be appreciated!
let userPlay;
do {
userPlay = prompt("rock, paper, or scissors?");
}
while (userPlay !== "rock" && userPlay !== "paper" && userPlay !== "scissors"); //prompt user for rock, scissors, or paper.
let compPlay = computerPlay();
function computerPlay() { //computer generates a random answer.
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
function playRound(playerSelection, computerSelection) { //plays a round of the game.
if (playerSelection === "rock") {
if (computerSelection === "rock") {
return "Draw!";
} else if (computerSelection === "paper") {
return "You lose! Paper beats rock.";
} else {
return "You win! Rock beats scissors.";
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
return "You win! Paper beats rock.";
} else if (computerSelection === "paper") {
return "Draw!";
} else {
return "You lose! Scissors beats paper.";
}
} else {
if (computerSelection === "rock") {
return "You lose! Rock beats scissors.";
} else if (computerSelection === "paper") {
return "You win! Scissors beats paper.";
} else {
return "Draw!";
}
}
}
console.log(playRound(userPlay, computerPlay));
You are using different variable names for the same thing computerSelection in one place, compPlay in another. Finally, in the console.log() at the end of the program, you are printing out the function computerPlay.
try this:
let userPlay = 'scissors';
do {
userPlay = prompt("rock, paper, or scissors?");
}
while (userPlay !== "rock" && userPlay !== "paper" && userPlay !== "scissors"); //prompt user for rock, scissors, or paper.
let computerSelection = computerPlay();
function computerPlay() { //computer generates a random answer.
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
function playRound(playerSelection, computerSelection) { //plays a round of the game.
if (playerSelection === "rock") {
if (computerSelection === "rock") {
return "Draw!";
} else if (computerSelection === "paper") {
return "You lose! Paper beats rock.";
} else {
return "You win! Rock beats scissors.";
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
return "You win! Paper beats rock.";
} else if (computerSelection === "paper") {
return "Draw!";
} else {
return "You lose! Scissors beats paper.";
}
} else {
if (computerSelection === "rock") {
return "You lose! Rock beats scissors.";
} else if (computerSelection === "paper") {
return "You win! Scissors beats paper.";
} else {
return "Draw!";
}
}
}
console.log(playRound(userPlay, computerSelection));

Categories