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()
Related
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());
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'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;
I am creating a rock paper scissors game where I have a playRound() function. I am trying to create a game() function where I can call this playRound() function multiple times with different results.
I want to use this game() function to play multiple rounds in order to find a winner
but I am still stuck on getting the playRound() to run multiple times.
With my current code, the playRound() function only runs once in the console.
Here is my code :
function playRound(playerSelection, computerSelection) {
const lose = "You Lose! Paper beats rock";
const win = "You Win! rock beats paper";
const tie = "its a tie";
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return lose;
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return win;
} else {
return tie;
}
}
function game() {
for (let i = 0; i < 3; i++) {
return playRound(playerSelection, computerSelection);
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const string = "ROck";
const playerSelection = string.toLowerCase() || string.toUpperCase();
const computerSelection = computerPlay();
console.log(game());
Not only is your game() function returning the results of the round thus leaving the loop... but you are setting the computerSelection only once... before calling the game() function.. so neither playerSelection or computerSelection ever changes.
I rearranged your code a bit and added an overall game score. Take a look.
function playRound(playerSelection, round) {
console.log("Round " + round);
const computerSelection = computerPlay();
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return 'lose';
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return 'win';
} else {
return 'tie';
}
}
function game() {
const lose = "You Lose! Paper beats rock";
const win = "You Win! Rock beats scissors";
const tie = "It's a tie";
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i < 4; i++) {
const result = playRound(playerSelection, i);
switch (result) {
case 'win':
console.log(win);
playerScore++;
break;
case 'lose':
console.log(lose);
computerScore++;
break;
default:
console.log(tie);
playerScore++;
computerScore++;
break;
}
}
console.log("Final Results: Player: " + playerScore + " Computer: " + computerScore);
if (playerScore > computerScore) {
console.log("You win the game!");
} else if (playerScore < computerScore) {
console.log("You lose the game.");
} else {
console.log("The game was an overall tie.");
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const playerSelection = "rock";
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())