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());
Related
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()
hope you all doing well. I am making a "Rock Paper Scissors" game for 'TheOdinProject', I completed it but here is the problem with loop, when I use it for console it works fine, and when calling a function its not looping. sorry for the bad english.
The last function game() is for looping, please help me to find the problem. thanks in advance.
function getComputerChoice() {
const gameChoice = ['rock', 'paper', 'scissor'];
const randomChoice = gameChoice[Math.floor(Math.random() * gameChoice.length)];
// console.log(randomChoice);
return randomChoice;
}
function playRound(playerSelection, computerSelection) {
switch (true) {
case (playerSelection === computerSelection):
return console.log('Game Tie, please try again.');
break;
case (playerSelection === 'rock' && computerSelection === 'scissor'):
let greetingRock = `You Choose: ${playerSelection} and`;
return console.log(`${greetingRock} You Win, Rock beats the scissor`);
break;
case (playerSelection === 'rock' && computerSelection === 'paper'):
let courageRock = `You Choose: ${playerSelection} and`;
return console.log(`${courageRock} You Lose, Paper beats the Rock`);
break;
case (playerSelection === 'scissor' && computerSelection === 'rock'):
let courageScissor = `You Choose: ${playerSelection} and`;
return console.log(`${courageScissor} You Lose, Rock beats the scissor`);
break;
case (playerSelection === 'scissor' && computerSelection === 'paper'):
let greetingScissor = `You Choose: ${playerSelection} and`;
return console.log(`${greetingScissor} You Win, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'scissors'):
let couragePaper = `You Choose: ${playerSelection} and`;
return console.log(`${couragePaper} You Lose, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'rock'):
let greetingPaper = `You Choose: ${playerSelection} and`;
return console.log(`${greetingPaper} You Win, Paper beats the Rock`);
break;
}
}
let userValue = prompt('Choose your Item:', '').toLowerCase();
if( userValue == null || userValue == "") {
prompt('Please Choose one of: Rock, Paper, scissor')
}
const playerSelection = userValue;
const computerSelection = getComputerChoice();
// console.log(playRound(playerSelection, computerSelection))
function game() {
for ( let i = 0; i < 5; i++ ) {
let playAgain = playRound(playerSelection, computerSelection);
return playAgain;
}
}
game();
// console.log(game());
function getComputerChoice() {
const gameChoice = ['rock', 'paper', 'scissor'];
const randomChoice = gameChoice[Math.floor(Math.random() * gameChoice.length)];
// console.log(randomChoice);
return randomChoice;
}
function playRound(playerSelection, computerSelection) {
switch (true) {
case (playerSelection === computerSelection):
console.log('Game Tie, please try again.');
break;
case (playerSelection === 'rock' && computerSelection === 'scissor'):
let greetingRock = `You Choose: ${playerSelection} and`;
console.log(`${greetingRock} You Win, Rock beats the scissor`);
break;
case (playerSelection === 'rock' && computerSelection === 'paper'):
let courageRock = `You Choose: ${playerSelection} and`;
console.log(`${courageRock} You Lose, Paper beats the Rock`);
break;
case (playerSelection === 'scissor' && computerSelection === 'rock'):
let courageScissor = `You Choose: ${playerSelection} and`;
console.log(`${courageScissor} You Lose, Rock beats the scissor`);
break;
case (playerSelection === 'scissor' && computerSelection === 'paper'):
let greetingScissor = `You Choose: ${playerSelection} and`;
console.log(`${greetingScissor} You Win, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'scissors'):
let couragePaper = `You Choose: ${playerSelection} and`;
console.log(`${couragePaper} You Lose, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'rock'):
let greetingPaper = `You Choose: ${playerSelection} and`;
console.log(`${greetingPaper} You Win, Paper beats the Rock`);
break;
}
}
function getPlayerChoice() {
const userValue = prompt('Choose your Item:', '').toLowerCase();
if (userValue == null || userValue == '') {
prompt('Please choose one of: Rock, Paper, Scissor');
}
const playerSelection = userValue;
const computerSelection = getComputerChoice();
console.log(playRound(playerSelection, computerSelection));
}
function game() {
let playAgain;
for (let i = 0; i < 5; i++) {
playAgain = getPlayerChoice();
}
}
game()
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.
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();
Greetings to the caring people of Stack Overflow.
I just recently started to learn JS and am now trying to make a CLI Rock Paper Scissors game. Yes, I know that I am the 100th person who has asked questions about it, but I could not find the 'no-make-sense' code through the code of other people. So just I ask for help from everyone who is not indifferent to helping a newbie!
The situation is this: the most common rules of a familiar game, but I can't get the counter to work, plus sometimes the text I type in is not recognized (I think the reason for the input comparison function).
Also, I'm sure that my func scopes are broken but where and why I can't figure out or trace it.
function computerPlay() {
let anyPick = Math.random();
if (anyPick < 0.3) {
return "Rock";
}
if (anyPick > 0.3 && anyPick < 0.6) {
return "Paper";
}
if (anyPick > 0.6) {
return "Scissors";
}
}
let aiScore = 0;
let playerScore = 0;
function battleRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "None of you are win or lose, cuz it is an equal!";
}
if (playerSelection === "rock" && computerSelection === "Scissors") {
playerScore += 1;
return "You Win! Rock beats Scissors";
}
if (playerSelection === "rock" && computerSelection === "Paper") {
aiScore += 1;
return "You Loose! Paper beats Rock";
}
if (playerSelection === "paper" && computerSelection === "Scissors") {
aiScore += 1;
return "You Loose! Scissors cut Paper";
}
if (playerSelection === "paper" && computerSelection === "Rock") {
playerScore += 1;
return "You Win! Paper beats Rock";
}
if (playerSelection === "scissors" && computerSelection === "Paper") {
playerScore += 1;
return "You Win! Scissors cut Paper";
}
if (playerSelection === "scissors" && computerSelection === "Rock") {
aiScore += 1;
return "You Loose! Rock beats Scissors";
} else return "U misspelled, try again";
}
function scores(aiScore, playerScore) {
if (aiScore > playerScore) {
return "CONGRAS, AI IS SMARTER THEN YOU!";
}
if (playerScore > aiScore) {
return "CONGRAS, YOU ARE SMARTER THEN AI";
}
}
for (let i = 0; i < 5; i++) {
const playerSelection = prompt(
"Choose: Rock, Paper or Scissors",
" "
).toLowerCase();
const computerSelection = computerPlay();
console.log("AI choose: " + computerSelection);
console.log(battleRound(playerSelection, computerSelection));
console.log("AI score: " + aiScore, "Player score: " + playerScore);
}
Please, indicate an obvious problem in the code and what exactly I need to replace.
Much obliged for any tips!
There are two main problems with your code that might be causing this issue,
You are setting the default prompt value to an empty space. By using:
prompt("Choose: Rock, Paper or Scissors", " ")
The default prompt value is an empty space, making it easier to mistype the value.
To fix this, I removed the default value and added the .trim() method to remove whitespace from the start and end of the input.
You are making impossible comparisons. In your code you made the comparison:
if (playerSelection === computerSelection) {
return ("None of you are win or lose, cuz it is an equal!");
}
This condition will never be true, as the playerSelection is always converted to lowercase e.g "rock", but the computerSelection's first letter is always uppercase e.g "Rock".
I added the .toLowerCase() method to the end of computerSelection before comparing.
Full code:
function computerPlay() {
let anyPick = Math.random();
if (anyPick < 0.3) {
return "Rock";
}
if (anyPick > 0.3 && anyPick < 0.6) {
return "Paper";
}
if (anyPick > 0.6) {
return "Scissors";
}
}
let aiScore = 0;
let playerScore = 0;
function battleRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection.toLowerCase()) {
return "None of you are win or lose, cuz it is an equal!";
}
if (playerSelection === "rock" && computerSelection === "Scissors") {
playerScore += 1;
return "You Win! Rock beats Scissors";
}
if (playerSelection === "rock" && computerSelection === "Paper") {
aiScore += 1;
return "You Loose! Paper beats Rock";
}
if (playerSelection === "paper" && computerSelection === "Scissors") {
aiScore += 1;
return "You Loose! Scissors cut Paper";
}
if (playerSelection === "paper" && computerSelection === "Rock") {
playerScore += 1;
return "You Win! Paper beats Rock";
}
if (playerSelection === "scissors" && computerSelection === "Paper") {
playerScore += 1;
return "You Win! Scissors cut Paper";
}
if (playerSelection === "scissors" && computerSelection === "Rock") {
aiScore += 1;
return "You Loose! Rock beats Scissors";
} else return "U misspelled, try again";
}
function finalScores() {
if (aiScore > playerScore) {
return "CONGRATS, AI IS SMARTER THEN YOU!";
}
if (playerScore > aiScore) {
return "CONGRATS, YOU ARE SMARTER THEN AI";
}
}
for (let i = 0; i < 5; i++) {
const playerSelection = (prompt("Choose: Rock, Paper or Scissors") ?? "")
.trim()
.toLowerCase();
const computerSelection = computerPlay();
console.log("AI choose: " + computerSelection);
console.log(battleRound(playerSelection, computerSelection));
console.log("AI score: " + aiScore, "Player score: " + playerScore);
}
console.log(finalScores())