Making "Rounds" in a Rock-Paper-Scissors Game? - javascript

I know this is a very popular/simple game to make, but I'm having a bit of trouble. I have made a rock-paper-scissors game in javascript and I've managed to make it work so that it will prompt the player to choose rock, paper, or scissors, get the computer to randomly pick an option, and a means for it to say "you lose" or "you win". The problem is that I'm required to make 5 rounds. That's the issue I'm having. I, for some reason, cannot seem to get the code to prompt the user 5 times. It only prompts the user once and runs the same code each time. My code is as follows:
function playRound(playerSelection) {
let computerSelection = getComputerSelection();
if (playerSelection == "rock") {
addToList(playerSelection, computerSelection);
if (computerSelection == "rock") {
result = "It's a tie";
}
else if (computerSelection == "paper") {
result = "You lost! Paper beats Rock";
computerScore++;
}
else {
result = "You won! Rock beats Scissors";
playerScore++;
}
}
else if (playerSelection == "paper") {
addToList(playerSelection, computerSelection);
if (computerSelection == "rock") {
result = "You won! Paper beats Rock";
playerScore++;
}
else if (computerSelection == "paper") {
result = "It's a tie";
}
else {
result = "You lost! Scissors beats Paper";
computerScore++;
}
}
else {
addToList(playerSelection, computerSelection);
if (computerSelection == "rock") {
result = "You lost! Rock beats Scissors";
computerScore++;
}
else if (computerSelection == "paper") {
result = "You won! Scissors beats Rock";
playerScore++;
}
else
result = "It's a tie";
}
h1.textContent = result;
player.textContent = playerScore;
computer.textContent = computerScore;
game();
}
function game() {
if (playerScore === 5) {
end.style.display = "block";
message.textContent = "You Won!";
}
else if (computerScore === 5) {
end.style.display = "block";
message.textContent = "You Lost!";
}
}
I would appreciate any help or direction that is given. I have tried putting my "playRound" function outside of the loop, but it gives me the same issue. What would make it prompt twice?
Thank you!

That's because you are asking for player's prompt only once i.e. it is outside the playRound method.
Try moving the following snippet into playround method.
const computerSelection = computerPlay();
const playerSelection = window.prompt("Enter your choice: ").toLowerCase();

I'm no expert in JS, so please correct me if i'm wrong, but what seems to be the case is that this variable:
const playerSelection = window.prompt("Enter your choice: ").toLowerCase();
is only initialized a single time with that function's return. (because it is outside any function) Accessing the variable only recalls it's value it was initialized with, causing the main loop to run over and over again with only that initial value.
replacing that line with someing like:
function getPlayerSelection(){
return window.prompt("Enter your choice:").toLowerCase()
}
and replacing everywhere you use playerSelection with getPlayerSelection() should fix this issue.

Related

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

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.

Rock-Paper-Scissors: the score is not recorded

I have created the function for the computer's choices and for the player's possible choices. However, for hours I've been trying to solve the issue of scorekeeping as it does not seem to work. I have set the requirements and I set global functions playerScore and computerScore = 0 and yet every time I call the gamescore function, the message which appears is "the tie" since for some reason the values of the two scores are always considered to be 0.
Any idea why might this be happening? I have done an extensive search online but in vain. I am still a beginner so on purpose, I use console.log and not innerHTML or any html/css style/button. The computerPlay() function is console-logged and every time go-live is refreshed, it gives a random choice so it works. For the second function, I do not know loops yet so I called it 5 times via console log to see the results. I also put specific playerSelection arguments so as to make the strings "You won, You lost, Draw again" cause if I did not, in all 5 times, the return was undefined and not one of these three strings/returns. If you refresh go live you will see the choices are changing randomly but the final sentence that should be given depending on the score after 5 rounds is always the same.
function computerPlay() {
let gameWords = ["Rock", "Paper", "Scissors"];
let randomWord = gameWords[Math.floor(Math.random() * gameWords.length)];
return randomWord;
};
console.log(computerPlay());
let playerScore = 0
let computerScore = 0
let draws = 0
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
if (computerSelection === "Rock") {
if (playerSelection === "rock") {
return "Draw again."
draws++
} else if (playerSelection === "paper") {
return "You won!"
playerScore++;
} else if (playerSelection === "scissors") {
return "You lost!"
computerScore++
};
};
if (computerSelection === "Paper") {
if (playerSelection === "paper") {
return "Draw again."
draws++
} else if (playerSelection === "rock") {
return "You lost..."
computerScore++
} else if (playerSelection === "scissors") {
return "You won!"
playerScore++
};
};
if (computerSelection === "Scissors") {
if (playerSelection === "scissors") {
return "Draw again."
draws++
} else if (playerSelection === "paper") {
return "You lost..."
computerScore++
} else if (playerSelection === "rock") {
return "You won"
playerScore++
};
};
console.log(playerScore);
};
const computerSelection = computerPlay();
console.log(playRound("RoCk", computerSelection));
console.log(playRound("Scissors", computerSelection));
console.log(playRound("PAper", computerSelection));
console.log(playRound("paper", computerSelection));
console.log(playRound("PAPER", computerSelection));
function gameScore() {
if (playerScore > computerScore) {
return "You won the game!";
} else if (playerScore < computerScore) {
return "You lost, try again.";
} else if (playerScore === computerScore) {
return "It is a tie.";
}
}
console.log(gameScore());
You code returns and then increase counters:
return "Draw again."
draws++
as you return counter increase is not called.

Javascript if/else not working. Odin project's Rock, paper, scissors

I’ve been trying to solve the Rock, Paper and Scissors project but I can’t figure out how to make the if/else statement. I did it a lot of times and finally I think I’m near to solve the issue, but the thing is, every time I run the program I get the wrong output.
For example, I used ‘Paper’ and the computer used ‘Rock’, but the console showed that ‘It’s a tie’, but in the code I wrote that if player chose paper and computer chose rock the message should have been ‘You win. Paper beats Rock’. The same happens when I choose ‘Paper’ and the computer chooses ‘Scissors’.
I used toLowerCase() method but after many changes, even when remove it and write exactly the words in the if/else this does not appear to be the problem.
What do I need to correct? Thank you so much!!!
This is the code:
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors!</title>
</head>
<body>
<script>
//Computer's selection
function computerPlay() {
let selectRandom = Math.floor(Math.random() * 3);
if (selectRandom === 0) {
return 'Rock';
} else if (selectRandom === 1) {
return 'Paper';
} else {
return 'Scissors';
}
}
console.log('Computer chose: ' + computerPlay());
//Play round between humand and computer
function playRound(playerSelection, computerSelection) {
//Change to lowercase
let player = playerSelection.toLowerCase();
let computer = computerSelection.toLowerCase();
//If player chooses rock
if (player === 'rock') {
if (computer === 'rock') {
return 'It\'s a tie. Try again'
} else if (computer === 'paper') {
return 'You loose. Paper beats Rock'
} else {
return 'You win. Rock beats scissors'
}
}
//If player chooses paper
else if (player === 'paper') {
if (computer === 'paper') {
return 'It\'s a tie. Try again'
}
if (computer === 'scissors') {
return 'You loose. Scissors beats Paper'
} else {
return 'You win. Paper beats Rock'
}
}
//If player chooses scissors
else {
if (computer === 'scissors') {
return 'It\'s a tie. Try again'
} else if (computer === 'rock') {
return 'You loose. Rock beats Scissors'
} else {
return 'You win. Scissors beats Paper'
}
}
}
const playerSelection = 'Paper';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
</script>
</body>
</html>
As you must have already known, every time you call computerPlay(), computer chooses a random value.
When you call computerPlay() in below statement, you get a random selection.
console.log('Computer chose: ' + computerPlay()); // Random selection.
And when you call the function again later in the code as shown below, you get another random selection.
const computerSelection = computerPlay(); // Random selection.
console.log(playRound(playerSelection, computerSelection));
This is the reason the output you see is not consistent with the actual result.
Solution: Move above console.log() statement to execute after computer selection, and log the returned value, don't call computerPlay() again. If you call it again, you'll get another random selection, not the one you are passing to playRound() function.
const computerSelection = computerPlay();
console.log('Computer chose: ' + computerSelection);
console.log(playRound(playerSelection, computerSelection));
Working Example:
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors!</title>
</head>
<body>
<script>
//Computer's selection
function computerPlay() {
let selectRandom = Math.floor(Math.random() * 3);
if (selectRandom === 0) {
return 'Rock';
} else if (selectRandom === 1) {
return 'Paper';
} else {
return 'Scissors';
}
}
//Play round between human and computer
function playRound(playerSelection, computerSelection) {
//Change to lowercase
let player = playerSelection.toLowerCase();
let computer = computerSelection.toLowerCase();
//If player chooses rock
if (player === 'rock') {
if (computer === 'rock') {
return 'It\'s a tie. Try again'
} else if (computer === 'paper') {
return 'You loose. Paper beats Rock'
} else {
return 'You win. Rock beats scissors'
}
}
//If player chooses paper
else if (player === 'paper') {
if (computer === 'paper') {
return 'It\'s a tie. Try again'
}
if (computer === 'scissors') {
return 'You loose. Scissors beats Paper'
} else {
return 'You win. Paper beats Rock'
}
}
//If player chooses scissors
else {
if (computer === 'scissors') {
return 'It\'s a tie. Try again'
} else if (computer === 'rock') {
return 'You lose. Rock beats Scissors'
} else {
return 'You win. Scissors beats Paper'
}
}
}
const playerSelection = 'Paper';
const computerSelection = computerPlay();
console.log('Computer chose: ' + computerSelection);
console.log(playRound(playerSelection, computerSelection));
</script>
</body>
</html>

My Console will only return two inputs or just one

This is my first time posting, I am having issues getting all selections to generate on the console. If I capitalise rock at the bottom it will only show the "Scissor" result. If I do not capitalise it, it will only show the other two results, but not scissors. Any guidance would be helpful.
function computerPlay() {
let selection = ["Rock", "Paper", "Scissors"];
let computerSelection = selection[Math.floor(Math.random() * selection.length)];
return computerSelection;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === "Rock") {
if (computerSelection === "Scissors")
return "You win mate, cheers!";
} else if (computerSelection === "Paper") {
return "You lost lad";
} else {
return "Draw";
}
}
const playerSelection = "rock"
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
The problem is that if the player selection matches "Rock", you ignore the else if and else blocks and go to see if the computer selected Scissors. If that is the case you return "You win mate, cheers!", otherwise you don't return anything, that's why you are getting undefined. If the player does not play Rock then you go into either else if or else statement but the player never wins.
Here's what your playRound function might look like to work properly:
function playRound(player, comp) {
const selection = ["Rock", "Paper", "Scissors"];
pl = selection.indexOf(player);
co = selection.indexOf(comp);
if (co === pl) {
return 'Draw';
} else if (co - pl == 1) {
return 'You lost lad'
} else {
return 'You win mate, cheers!'
}
}
Here's a jsfiddle with a working code sample: https://jsfiddle.net/qjp1y1mg/
This code works fine for me. Try this. It is your code, but something was wrong (a bracket in a wrong place) and I have changed it.
function playRound(playerSelection, computerSelection) {
if (playerSelection === "Rock"){
if (computerSelection === "Scissors")
return "You win mate, cheers!";
else if (computerSelection === "Paper"){
return "You lost lad";
}
else {return "Draw";}
}
}
In your code this bracket was wrong. Because you are excluding other occurrences
if (playerSelection === "Rock") {
if (computerSelection === "Scissors")
return "You win mate, cheers!";
**}**
You're missing a curly bracket after the first inner if statement. The indentation of the code should be a sign that it is not nested the way you want it.
function playRound(playerSelection, computerSelection) {
if (playerSelection === "Rock") {
if (computerSelection === "Scissors"{
return "You win mate, cheers!";
} else if (computerSelection === "Paper") {
return "You lost lad";
} else {
return "Draw";
}
}
}
Here it is fixed. In future scan through your code and ask yourself which opening brackets correspond to whch closing brackets.

Categories