Loop prompt if a value is empty / wrong? - javascript

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

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

Rock,Paper,Scissors round counter in JavaScript

I'm trying to make a console version of rock paper scissors. The game is working for now but I can't run the for loop, what I want to do is at the end of each round, the console will say what round we are in and tell who won the current round. It will be the Best of 5 and the winner will be determined in round 5.
Since I'm a beginner I couldn't try too much. I know my code is not clean and complicated because I proceed by trying and I'm also new to Stackoverflow, if there is something missing in the topic, I apologize in advance for those.
// PLAYER CODES
let playerSelection = prompt('Do you choose Rock, Paper or Scissors?')
if (playerSelection === 'Rock' || playerSelection === 'Paper' || playerSelection === 'Scissors') {
console.log("You chose " + `${playerSelection}`);
} else {
console.log('Error! Pick Rock, Paper or Scissors')
}
// COMPUTER CODES
let computerSelection = getComputerChoice();
function getComputerChoice() {
let choices = ['Rock', 'Paper', 'Scissors'];
let random = choices[Math.floor(Math.random() * 3)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
return ('Draw')
} else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) {
return ('Player Wins! Rock beats Scissors.')
} else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) {
return ('Player Wins! Scissors beats Paper.')
} else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) {
return ('Player Wins! Paper beats Rock.')
} else if ((computerSelection === 'Scissors') && (playerSelection === 'Paper')) {
return ('Computer Wins! Scissors beats Paper.')
} else if ((computerSelection === 'Paper') && (playerSelection === 'Rock')) {
return ('Computer Wins! Paper beats Rock.')
} else if ((computerSelection === 'Rock') && (playerSelection === 'Scissors')) {
return ('Computer Wins! Rock beats Scissors.')
}
}
function game() {
for (let i = 1; i < 6; i++){
playRound(playerSelection, computerSelection);
if (i == 1)
return ('Round 1')
else if (i == 2)
return ('Round 2')
else if (i == 3)
return ('Round 3')
else if (i == 4)
return ('Round 4')
else if (i == 5)
return ('Round 5')
}
}
console.log("Computer chose " + `${computerSelection}`);
console.log(playRound(playerSelection, computerSelection));
console.log(game(playRound));
You have to put the sections to get the player and computer choices inside the loop. I fixed some other problems, too.
// PLAYER CODES
function getPlayerChoice () {
let playerSelection = prompt('Do you choose Rock, Paper or Scissors?')
if (playerSelection === 'Rock' || playerSelection === 'Paper' || playerSelection === 'Scissors') {
console.log("You chose " + `${playerSelection}`);
return playerSelection
} else {
console.log('Error! Pick Rock, Paper or Scissors')
return getPlayerChoice()
}
}
// COMPUTER CODES
function getComputerChoice() {
let choices = ['Rock', 'Paper', 'Scissors'];
let random = choices[Math.floor(Math.random() * 3)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
return ('Draw')
} else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) {
return ('Player Wins! Rock beats Scissors.')
} else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) {
return ('Player Wins! Scissors beats Paper.')
} else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) {
return ('Player Wins! Paper beats Rock.')
} else if ((computerSelection === 'Scissors') && (playerSelection === 'Paper')) {
return ('Computer Wins! Scissors beats Paper.')
} else if ((computerSelection === 'Paper') && (playerSelection === 'Rock')) {
return ('Computer Wins! Paper beats Rock.')
} else if ((computerSelection === 'Rock') && (playerSelection === 'Scissors')) {
return ('Computer Wins! Rock beats Scissors.')
}
}
function game() {
for (let i = 1; i < 6; i++){
console.log('Round ' + i)
let playerSelection = getPlayerChoice();
let computerSelection = getComputerChoice();
console.log("Computer chose " + `${computerSelection}`);
console.log(playRound(playerSelection, computerSelection));
}
}
game()

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

JS CLI RPS game issue

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

How to display in console the result of ROCK, PAPER, SCISSOR GAME Javascript

I`m currently stuck with a rock, paper, scissors game in javascript.
I need to display in console something like this:
Computer choice: “Rock”
User choice: “Paper”
User wins!
How can I implement this in the code below.
let userSelection = userPlay();
function userPlay() {
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
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 "Computer wins!";
} else {
return "User wins!";
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
return "User wins!";
} else if (computerSelection === "paper") {
return "Draw!";
} else {
return "Computer wins!";
}
} else {
if (computerSelection === "rock") {
return "Computer wins!";
} else if (computerSelection === "paper") {
return "User wins!";
} else {
return "Draw!";
}
}
}
console.log(playRound(userPlay, computerSelection));
I have swapped the position of function calls for better readability. Idea is to store the result of each function call into a variable and print it.
function userPlay() {
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
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 "Computer wins!";
} else {
return "User wins!";
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
return "User wins!";
} else if (computerSelection === "paper") {
return "Draw!";
} else {
return "Computer wins!";
}
} else {
if (computerSelection === "rock") {
return "Computer wins!";
} else if (computerSelection === "paper") {
return "User wins!";
} else {
return "Draw!";
}
}
}
var userChoice = userPlay();
var computerSelection = computerPlay();
var result = playRound(userChoice, computerSelection)
console.log("user's choice", userChoice);
console.log("computer's choice", computerSelection);
console.log("Result is", result);
I'm not sure if I'm too late for an answer but I have refactored the code a bit (it can be refactored a bit more I think, but I'll let you do that).
let playerSelection = getNumber();
let computerSelection = getNumber();
function getNumber() { //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.
let message = '';
let random = ["rock", "paper", "scissors"];
let playerSelectionIndex = random.indexOf(playerSelection);
let computerSelectionIndex = random.indexOf(computerSelection);
switch (true) {
case(playerSelectionIndex == computerSelectionIndex + 1):
// Scissors beats rock
case((playerSelectionIndex + 2) == computerSelectionIndex):
message = 'You Win';
break;
case (computerSelectionIndex == playerSelectionIndex):
message = 'Draw';
break;
default:
message = 'You lose';
break;
}
return message;
}
console.log(playRound(playerSelection, computerSelection));

Categories