The odin project rock, paper, scissor always a tie - javascript

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();

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());

Loop prompt if a value is empty / wrong?

I'm doing a simple rock, paper, exercise on console (from The Odin Project) and I am stucked in some point. I want the prompt that selects rock, paper or scissors to keep showing if the user input is empty or wrong (if is a different string from the variable choices) and I'm not getting the reuslt I want, the alert shows, yes, but it shows whether if you input a correct value, a wrong value or if you left it empty and the prompt also finishes after the loop for ends which I only want to finish if the input is "rock", "paper" or "scissors".
Can someone enlight me here? I'm just blank.
const choices = ["rock", "paper", "scissors"];
let playerScore = 0;
let computerScore = 0;
let playerName = "";
function getComputerChoice() {
let random = choices[Math.floor(Math.random() * choices.length)];
console.log(random);
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie";
} else if (playerSelection === "rock") {
if (computerSelection === "scissors") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "paper") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "scissors") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "scissors") {
if (computerSelection === "paper") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "rock") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
}
}
function playerChoice() {
const userChoice = prompt("Rock, paper, scissors").toLowerCase();
if (userChoice == null || userChoice !== choices) {
alert("Empty or wrong choice!");
} else if (choices.includes(userChoice)) {
return userChoice;
}
}
function getPlayerName() {
playerName = prompt("What is your name?");
return playerName;
}
function game () {
getPlayerName();
console.log(`Welcome ${playerName}`)
for (i = 0; i < 3; i++) {
const computerSelection = getComputerChoice();
const playerSelection = playerChoice();
console.log(playRound(playerSelection, computerSelection));
}
if (playerScore > computerScore) {
return "Game over! Player wins!";
} else if (playerScore < computerScore) {
return "Game over! Player loses!";
} else {
return "Game over, draw!";
}
}
console.log(game());
Thank you very much.
The problem is you're checking whether the input is the same as the array choices. using the include function here will check that the user's choice is in the array
const choices = ["rock", "paper", "scissors"];
let playerScore = 0;
let computerScore = 0;
let playerName = "";
function getComputerChoice() {
let random = choices[Math.floor(Math.random() * choices.length)];
console.log(random);
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie";
} else if (playerSelection === "rock") {
if (computerSelection === "scissors") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "paper") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "scissors") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "scissors") {
if (computerSelection === "paper") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "rock") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
}
}
function playerChoice() {
const userChoice = prompt("Rock, paper, scissors").toLowerCase();
console.log(choices.includes(userChoice))
if (userChoice == null || !choices.includes(userChoice)) {
alert("Empty or wrong choice!");
} else if (choices.includes(userChoice)) {
return userChoice;
}
}
function getPlayerName() {
playerName = prompt("What is your name?");
return playerName;
}
function game () {
getPlayerName();
console.log(`Welcome ${playerName}`)
for (i = 0; i < 3; i++) {
const computerSelection = getComputerChoice();
const playerSelection = playerChoice();
console.log(playRound(playerSelection, computerSelection));
}
if (playerScore > computerScore) {
return "Game over! Player wins!";
} else if (playerScore < computerScore) {
return "Game over! Player loses!";
} else {
return "Game over, draw!";
}
}
console.log(game());
Edit: Also you might want to change this line as a null input won't have the attribute .toLowerCase()
const userChoice = prompt("Rock, paper, scissors").toLowerCase();

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.

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

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.

(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