JavaScript invalid input condition - javascript

I am new to JavaScript.Other day I made a game of Rock Paper Scissor.The game works fine but I wanted to know that can you put up a condition that if the User chooses to input invalid choice an alert box appears and says invalid input something like that!
Here is my code!
var userchoice=prompt("Wanna play Rock, Paper and Scissors?");{
if (userchoice!="paper") {
alert("Invalid ID");
}
else if (userchoice!="scissors") {
alert("Invalid ID");
}
else (userchoice!="rock") {
alert("Invalid ID");
}
}
var computerchoice=Math.random();{
if(computerchoice<0.34){
console.log(computerchoice="paper");
}
else if (computerchoice<=0.67) {
console.log(computerchoice="rock");
}
else{
console.log(computerchoice="scissors");
}
};
var compare=function(choice1,choice2){
if (choice1===choice2){
console.log("The game was a tie!");
}
else if (choice1==="rock") {
if (choice2==="scissors") {
console.log("rock wins!");
}
else{
console.log("paper wins!")
}
}
else if(choice1==="paper"){
if (choice2==="rock") {
console.log("paper wins!");
}
else{
console.log("scissors wins!");
}
}
else if (choice1==="scissors") {
if (choice2==="paper") {
console.log("scissors wins!")
}
else {
console.log("rock wins!");
}
}
};
compare(userchoice,computerchoice);
console.log("User: "+userchoice);
console.log("Computer: "+computerchoice);
//End of Game

Here is some compacted code to figure out if any of the choices are invalid. It alerts if there was an invalid choice, but you should change that to a more appropriate behavior.
var VALID_CHOICES = ['rock', 'paper', 'scissors']
var choice1 = 'rock', choice2 = 'something invalid'
var invalidChoice = false
;[choice1, choice2].forEach(function(choice) {
if (VALID_CHOICES.indexOf(choice) === -1) invalidChoice = true
})
if (invalidChoice) alert('Picked an invalid choice')

You can have a function like this, that will prompt, but also will check if the choice is valid.
function ask(q) {
var choice = prompt(q);
if (choice != 'scissors' && choice != 'rock' && choice != 'paper') {
alert('Invalid input. Only "scissors", "rock" or "paper" are allowed.');
return false;
} else {
return choice;
}
}
console.log('the choice is:',ask("Wanna play Rock, Paper and Scissors?"));
The if checks if the choice is not "scissors" or "rock" or"paper", if is invalid it will alert, and return false.
But if the choice is valid it will return choice.

You can keep compare the way you defined it.
trim() removes white spaces before and after user answer
toLowerCase() converts uppercase letters to lowercase
var promptUser = function(text){
var userAnswer = prompt(text);
var cleanAnswer = userAnswer.trim().toLowerCase();
if(['paper', 'scissors', 'rock'].indexOf(cleanAnswer) === -1) {
alert('Invalid choice: ' + cleanAnswer);
}
return cleanAnswer;
}
var computerPlays = function() {
var computerchoice = Math.random();
if(computerchoice<0.34){
computerchoice="paper";
} else if (computerchoice<=0.67) {
computerchoice="rock";
} else {
computerchoice="scissors";
}
return computerchoice;
};
var userChoice = promptUser("Wanna play Rock, Paper and Scissors?");
var computerChoice = computerPlays();
console.log('user picks:', userChoice);
console.log('computer picks:', computerChoice)
compare(userChoice,computerChoice);

You could use Array.prototype.indexOf(). Try the demo below:
function newGame(msg) {
var allowed = ["rock","paper","scissors"],
user = allowed.indexOf(prompt((msg||'Feeling lucky?') + ' Choose "rock", "paper" or "scissors":').trim().toLowerCase()),
comp = Math.floor(Math.random()*3);
if(user < 0) return newGame("Invalid ID!");
console.log("You chose "+ allowed[user] +". Computer chose "+ allowed[comp] +".");
if(user == comp)
console.log('The game was a tie!');
else if([1,-2].indexOf(comp-user) > -1)
console.log('Computer wins with ' + allowed[comp] + '!');
else
console.log('You win with ' + allowed[user] + '!');
}
<button onclick="newGame()">New game</button>

Related

Showing the same result in Rock Paper Scissors - Java Script

**I am trying to create rock paper scissors in java script and The below is the code I am executing, It is showing "The match is draw! play again" everytime. What goes wrong?
First taking the user input and checking the correctness. Generating the computer input by Math.random and assigning them RPS based on the output. Finally comparing both to determine the winner.**
const getUserChoice = function(userInput){
userInput = userInput.toLowerCase();
if (userInput === 'rock'|| userInput ==='paper'|| userInput ==='scissors'){
return userInput;
}else {
console.log('Error');
}
}
userChoice = getUserChoice('rock');
console.log(getUserChoice('rock'));
const getComputerChoice = function(){
randomNumber = Math.floor(Math.random()*3);
switch(randomNumber) {
case 0:
return 'rock';
break;
case 1:
return 'paper';
break;
case 2:
return 'scissors';
break;
default:
return 'error';
}
}
computerChoice = getComputerChoice();
console.log(getComputerChoice());
const determineWinner = function(userChoice, computerChoice){
if (userChoice === computerChoice){
return 'The match is draw! Play again.';
}
if (userChoice === 'rock'){
if (computerChoice === 'paper'){
return 'you lost';
}else{
return 'you won';
}
}
if (userChoice === 'paper'){
if (computerChoice === 'rock'){
return 'you won';
}else{
return 'you lost';
}
}
if (userChoice === 'scissors'){
if (computerChoice === 'rock'){
return 'you lost';
}else{
return 'you won';
}
}
}
console.log(determineWinner());**strong text**
On your bottom line, you are not passing any parameters through.
Change it to:
console.log(determineWinner(userChoice, computerChoice));**strong text**
Currently, the first line of your determineWinner function is checking if null is equal to null (which it is), so is returning a draw.
Here you go. Checkout the below answer:
const getUserChoice = function(userInput){
userInput = userInput.toLowerCase();
if (userInput === 'rock'|| userInput ==='paper'|| userInput ==='scissors'){
return userInput;
}else {
console.log('Error');
}
}
const userChoice = getUserChoice('rock');
const getComputerChoice = function(){
const randomNumber = Math.floor(Math.random() * 3);
switch(randomNumber) {
case 0:
return 'rock';
break;
case 1:
return 'paper';
break;
case 2:
return 'scissors';
break;
default:
return 'error';
}
}
const computerChoice = getComputerChoice();
const determineWinner = function(userChoice, computerChoice){
console.log('user choice: ', userChoice);
console.log('computer choice: ', computerChoice);
if (userChoice === computerChoice){
return 'The match is draw! Play again.';
}
if (userChoice === 'rock'){
if (computerChoice === 'paper'){
return 'you lost';
} else {
return 'you won';
}
}
if (userChoice === 'paper'){
if (computerChoice === 'rock'){
return 'you won';
}else{
return 'you lost';
}
}
if (userChoice === 'scissors'){
if (computerChoice === 'rock'){
return 'you lost';
}else{
return 'you won';
}
}
}
console.log(determineWinner(userChoice, computerChoice));
It's simply because you are not passing the arguments to the determineWinner function.
Change the last line to:
determineWinner(userChoice,computerChoice);
Currently it's considering both choices as null and returning you the output as draw!

Testing if the user input value is in a given array (JavaScript)

I just created a five rounds rock-paper-scissors game using vanilla JavaScript. The program runs just fine so far except for the fact every time I start the game for the very first time it will take any user input as invalid no matter what and won't count that round.
This is my code:
// Global variables
let playerWins = 0;
let computerWins = 0;
let array = [];
let validInput = 0;
let newRound = "";
// This function generates a computer selection
const computerPlay = () => {
array = ["rock", "paper", "scissors"]
return array[Math.floor(Math.random() * array.length)];
}
// This function stores player selection
const playerSelection = (selection) => {
selection = prompt("Enter: 'Rock', 'Paper' or 'Scissors'").toLowerCase();
validInput = array.indexOf(selection);
console.log(validInput);
// This loop will validate user input is correct
while (validInput === -1) {
alert("Invalid input, try again");
selection = prompt("Enter 'Rock', 'Paper' or 'Scissors'").toLowerCase();
validInput = array.includes(selection);
}
return selection;
}
// This function plays a single round of Rock-Paper-Scissors
const playRound = (playerSelection, computerPlay) => {
// If both players select the same item
if (playerSelection === computerPlay) {
return alert("It's a tie!");
}
// If player selects "Rock"
if (playerSelection === "rock") {
if (computerPlay === "scissors") {
playerWins += 1;
return alert("Rock crushes scissors: YOU WIN!!!");
} else {
computerWins += 1;
return alert("Paper covers rock: YOU LOOSE!!!");
}
}
// If player selects "Paper"
if (playerSelection === "paper") {
if (computerPlay === "rock") {
playerWins += 1;
return alert("Paper covers rock: YOU WIN!!!");
} else {
computerWins += 1;
return alert("Scissors cuts paper: YOU LOOSE!!!");
}
}
// If player selects "Scissors"
if (playerSelection === "scissors") {
if (computerPlay === "rock") {
computerWins += 1;
return alert("Rock crushes scissors: YOU LOOSE!!!");
} else {
playerWins += 1;
return alert("Scissors cuts paper: YOU WIN!!!");
}
}
}
// This function keeps score and reports a winner or loser at the end
const trackWins = (pw, cw) => {
alert("COMPUTER WINS: " + cw + "\nPLAYER WINS: " + pw)
if (pw > cw) {
alert("YOU WIN THIS ROUND, CONGRAX!!!")
} else if (cw > pw) {
alert("YOU LOOSE THIS ROUND, SO BEST LUCK FOR THE NEXT TIME :_(")
} else {
alert("IT'S A TIE")
}
}
// This function creates a 5 round game
const game = () => {
for (let i = 0; i < 5; i++) {
playRound(playerSelection(), computerPlay());
}
trackWins(playerWins, computerWins);
}
do {
game();
newRound = prompt("Do yo want to play another round? Type 'y' to continue or any other key to exit").toLowerCase();
} while (newRound === "y");
alert("It was a good game, bye for now!")
I will appreciate any ideas to fix this problem or improve my script, thank you in advance!
Your posted code can be simplified to better reflect question - say, you have an array, and a variable that stores user input. How do you test if the input value is in the array?
var arr=['Rock','Paper','Scissors'];
var inp='Rock'; //user input
You could use a while loop, but there's a much faster way:
var options={'rock':0,'paper':1,'scissors':2}
var inp='Rock'; //user input
var ninp=inp.toLowerCase().trim(); //normalize input
var pick=(options[ninp]);
if (pick==null) // invalid selection
if (pick==0) //rock
if (pick==1) //paper
if (pick==2) //scissors
The code can be further cleaned up with a switch:
switch (pick){
case 0: ... break; //rock
case 1: ... break; //paper
case 2: ... break; //scissors
default: //invalid
}

error defining computerChoice in the function getComputerChoice - javascript program

I am doing a simple rock, paper, scissors program in the codeacademy javascript course. This first one is very simple and much of what is here is the way they guided me. I know the entire thing can be written better but that comes later. Program works partially but never seems to define the computerChoice variable. I think the issue is in lines 15-18 but not sure. I did try changing the strings to integers in lines 42, 49 & 58 but that did not solve the issue.
Can anyone look at my code and offer guidance.
//function to get the user's choice
const getUserChoice = userInput => {
userInput =
userInput.toLowerCase();
//if stmt to make sure input is valid
if (userInput === 'rock' || 'scissors' || 'paper') {
return userInput;
} else {
console.log('Invalid selection');
}//end else
}//end getUserChoice function
//function to get computer choice
const getComputerChoice = () => {
Math.floor(Math.random() * 3);
//switch case to verify & return result
switch (getComputerChoice) {
case 0:
return 'rock';
break;
case 1:
return 'paper';
break;
case 2:
return 'scissors';
break;
default:
console.log('Invalid');
break;
}//end switch
}//end getComputerChoice
//function to determine the winner
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return 'The game is a tie';
}
if (userChoice === 'rock') {
if (computerChoice === 'paper') { return 'You Won!'; }
} // end userchoice is rock
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'The computer won!';
} else {
return 'You won!';
}
} // end userchoice is paper
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'The computer won!';
} else {
return 'You won!';
}
} //end userchoice is scissors
}//end winner function
//function to play the game
const playGame = () => {
const userChoice = getUserChoice('rock');
const computerChoice = getComputerChoice();
console.log('You threw: ' + userChoice);
console.log('The computer threw: ' + computerChoice);
//call funtion to determine winner
console.log(determineWinner(userChoice, computerChoice));
}//end playGame
//function calls
playGame();
Problem
After a more thorough examination, there were a few errors. Demo 1 addresses each of these errors. Details are commented in the demo. There is a Plunker of Demo 1 as well.
At first, I had started on a working demo without the benefit of your updated post. Demo 2 is functioning as well and is helpful if you want to consider an alternative way to meet your objective.
Plunker
Demo 1
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
//if stmt to make sure input is valid
if (userInput === 'rock' || 'scissors' || 'paper') {
return userInput;
} else {
console.log('Invalid selection');
} //end else
}; //end getUserChoice function
//function to get computer choice
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On each case there was a return before every break
A return statement always ends the block so break
was useless and in the process the switch useless.
Changed getComputerChoice into a declared function
Saved the results of switch in a variable
Returned the value as expected
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function getComputerChoice() {
let compPick = Math.floor(Math.random() * 3);
console.log('compPick: ' + compPick);
var psr;
//switch case to verify & return result
switch (compPick) {
case 0:
psr = 'rock';
break;
case 1:
psr = 'paper';
break;
case 2:
psr = 'scissors';
break;
default:
console.log('Invalid');
break;
} //end switch
return psr;
}
//function to determine the winner
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return 'The game is a tie';
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Missing the else portion of conditional statement,
Whenever user threw a rock and computer threw a
scissor, the result was undefined.
Added the else portion, now all 7 condition are met. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'You Lost!';
} else {
return "You Won!"
}
} // end userchoice is rock
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'You Lost!';
} else {
return 'You won!';
}
} // end userchoice is paper
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'You Lost!';
} else {
return 'You won!';
}
} //end userchoice is scissors
}; //end winner function
//function to play the game
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Added a <select> element so testing is properly done
Changed playGame() to a declared function and the
callback function for the change event listener
Note that playGame is passing a value. This value is from the <select>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function playGame(psr) {
const userChoice = getUserChoice(psr);
const computerChoice = getComputerChoice();
console.log('You threw: ' + userChoice);
console.log('The computer threw: ' + computerChoice);
//call funtion to determine winner
console.log(determineWinner(userChoice, computerChoice));
} //end playGame
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Reference the <select> tag
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
var sel = document.getElementById('psr');
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Register the change event on the <select> tag
When change event occurs on select#psr, playGame() is
called and it passes the value of select#psr thru
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
sel.addEventListener('change', function(e) {
playGame(this.value);
});
select,
option {
font: inherit
}
#psr {
margin: 30px 0 0 30px
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id='psr'>
<option>---</option>
<option value='paper'>Paper</option>
<option value='scissors'>Scissors</option>
<option value='rock'>Rock</option>
</select>
</body>
</html>
Demo 2
/* Using HTMLFormControlsCollection
\ Reference the form and...
*/
var game = document.forms.psrGame;
/* reference the form's form controls
*/
var ctrl = game.elements;
/* This is an Object Literal.
\ It's storing data for easy reuse
*/
var PSR = {
player: 0,
opponent: 0,
action: ['📃Paper', '✂️Scissors', '🗿Rock'],
outcome: ['Tied', 'Player Won', 'Player Lost'],
won: 0,
lost: 0,
tied: 0
};
/* Register the click event on fieldset#set
\ Callback function is choice()
*/
ctrl.set.addEventListener('click', choice);
// Callback function
function choice(e) {
/* if the clicked button (e.target) is NOT
|| the registered node (e.currentTarget)...
|| if the clicked node is a BUTTON...
*/
if (e.target !== e.currentTarget) {
if (e.target.tagName === 'BUTTON') {
// Get clicked button's id
var z = parseInt(e.target.id, 10);
PSR.player = z;
//console.log('z: ' + z);
// Get a randomly generated number 0-2
var x = rand(0, 2);
PSR.opponent = x;
//console.log('x: ' + x);
// Determine P.S.R. for player
var pick = PSR.action[z];
//console.log('Picked: ' + pick);
// Determine P.S.R. for opponent
var verse = PSR.action[x];
//console.log('Verses: ' + verse);
// Display P.S.R of player and opponent
ctrl.choice.value = pick;
ctrl.against.value = verse;
}
// Get the outcome and display it
var us = determine(PSR);
ctrl.view.value = us;
return us;
}
/* Prevent event bubbling thereby isolating the
|| the click events from the rest of the form
*/
e.stopPropagation();
}
/* Through a gauntlet of conditions
|| it is determined whether player
|| lost, won, or tied.
*/
function determine(PSR) {
var Z = PSR.player;
var X = PSR.opponent;
var msg;
if (Z === X) {
msg = PSR.outcome[0];
++PSR.tied;
} else if (Z === 0 && X === 2) {
msg = PSR.outcome[1];
++PSR.won;
} else if (Z === 1 && X === 0) {
msg = PSR.outcome[1];
++PSR.won;
} else if (Z === 2 && X === 1) {
msg = PSR.outcome[1];
++PSR.won;
} else {
msg = PSR.outcome[2];
++PSR.lost;
}
/* This is a Template Literal which will
|| display the player's wins, losses, and ties
*/
var totals = `Won: ${PSR.won} Lost: ${PSR.lost} Tied: ${PSR.tied} `;
ctrl.score.innerHTML = totals;
return msg;
}
// Utility to generate random integers
function rand(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
body {
font-size: 16px;
}
#set {
margin-bottom: 10px;
}
input,
button,
output,
label {
font: inherit;
display: inline-block
}
button {
width: 9ch
}
.as-console-wrapper {
max-width: 30%;
margin-left: 70%
}
#view {
font-weight: 900;
color: crimson
}
legend {
font-variant: small-caps;
font-size: 1.2em;
}
<form id='psrGame'>
<fieldset id='set'>
<legend>Paper, Scissors, Rock</legend>
<button id='0' type='button'>Paper</button>
<button id='1' type='button'>Scissors</button>
<button id='2' type='button'>Rock</button>
</fieldset>
<label><b>Player: </b>
<output id='choice'></output>
</label>
<hr>
<label><output id='view'></output></label>
<label style='float:right'><output id='score'></output></label>
<hr>
<label><b>Opponent:</b>
<output id='against'></output>
</label>
Line 18 should be
switch (Math.floor(Math.random() * 3)) {
Whatever value you pass to switch is what's compared against the values of the cases. The switch cases check a random integer from 0 to 2, so pass that generated random number to switch.

How can I prevent console from printing in JavaScript game?

I've been practicing a game with JavaScript, and was wondering how to prevent the console from printing when a user makes an ill defined choice?
Here is the code:
var user = prompt("Do you choose rock, paper or scissors?");
var computer = Math.random();
if (computer < 0.34) {
computer = "rock";
}
else if (computer <= 0.67) {
computer = "paper";
}
else {
computer = "scissors";
}
console.log("Computer Chooses: " + computer);
console.log("User Chooses: " + user);
var compare = function (computer, user) {
if (computer === "rock") {
if (user === "scissors") {
return "Computer wins by choosing rock!";
}
}
else if (computer === "scissors") {
if (user === "paper") {
return "Computer wins by choosing scissors!";
}
}
else if (computer === "paper") {
if (user === "rock") {
return "Computer wins by choosing paper!"
}
}
if (computer === user) {
return ("It is a tie!")
}
else if (user === "paper") {
if (computer === "rock") {
return ("You win by choosing paper!")
}
}
else if (user === "rock") {
if (computer === "scissors") {
return ("You win by choosing scissors!")
}
}
else if (user === "scissors") {
if (computer === "paper") {
return ("You win by choosing scissors!")
}
}
***if (user !== "rock" && user !== "paper" && user !== "scissors") {
confirm(user + " is an invalid entry.");
}***
};
compare(computer, user);
At the end I snipped the bit of code that gives the user an indication that he has put in the wrong characters. What I am wondering is:
How do I keep anything from displaying to the console once someone has put in the wrong input?
One option would be to keep asking the user for a valid input until a valid input is given:
while (user != "rock" && user != "paper" && user != "scissors") {
user = prompt("Do you choose rock, paper or scissors?")
if (user == null) {
break;
}
};
if (user != null) {
...
}
http://jsfiddle.net/2w3pt5yy/3/
make the validation of user input at the beginning . if user passes only show the code else show error.
var user = prompt("Do you choose rock, paper or scissors?");
if(user !== "rock" && user !== "paper" && user!== "scissors") {
confirm(user + " is an invalid entry.");
} else {
// code for process
}
You can add this code on top of your js code
var console = {};
console.log = function(){};
You have more if statements than is necessary; you can simplify the logic.
var getComputerMove = function () {
// equivalent of Math.floor
// aka it grabs the integer component of `Math.random() * 3`
// either 0, 1, or 2
return (Math.random() * 3) | 0;
}
var playRockPaperScissors = function () {
var moves = [ "rock", "paper", "scissors" ]
, user = ""
, computer = getComputerMove();
// while `user` is not in the `moves` array
// `Array.indexOf` returns -1 if an element is not in the array
// prompt the user for his move
while (moves.indexOf(user.toLowerCase()) == -1) {
user = prompt("Rock, paper, or scissors?");
}
// this is where you can save yourself all that typing and think out
// the possible movesets:
// item: rock < paper < scissors < rock
// index: 0 < 1 < 2 < 0
// so, the computer wins if its choice is greater than the user's,
// or if the computer chose "rock" and the user chose scissors
// we can translate this to
// user < computer || (computer == 0 && user == 2)
var userIndex = moves.indexOf(user.toLowerCase());
// uncomment, if you want to see the moves
// console.log("user:", user, "computer:", moves[computer]);
if (userIndex < computer || (userIndex == 2 && computer == 0) {
alert("Computer wins!");
} else {
alert("User wins!");
}
}

What is wrong with the conditions, I can't validate user input in javascript

I am trying to ensure the user insert the right string but so far it seems the solution just loves eluding me. Its a mini paper, scissors, rock game. If the user inputs some other string except the allowedString, he should be asked to continue then the prompt dialogue will then come up. Here is the code.
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
}
else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);
var compare = function(choice1,choice2)
{
ch(choice1);
if (choice1 === choice2){
return"The result is a tie!";
}
else if (choice1==="rock"){
if (choice2==="scissors"){
return "rock wins";
}
else {
return"paper wins";
}
}
else if(choice1==="paper"){
if(choice2==="rock"){
return"paper wins";
}
else {
return"scissors wins";
}
}
else if (choice1==="scissors"){
if(choice2 ==="rock"){
return"rock wins";
}
else{
return"scissors wins";
}
}
}
var ch = function(user)
{
allowedString = ["paper", "scissors", "rock"];
if (!Boolean(user in allowedString)){
if (confirm("Your choice is invalid, Do you want to try again?")) {
userChoice = prompt("Choose rock, paper or scissors?");
compare(userChoice, computerChoice);
}
else{
console.log("Thanks for playing");
}
}
else return;
}
compare(userChoice, computerChoice);
You had a little imprecision in ch validation function. It always returned error.
if (allowedString.indexOf(user) > -1)
{
console.log('ok');
return;
}
I think now it works as expected. Let me know if it's ok.
Fiddle
just for fun i wrote my version:
var rules = {
rock: {beat: ['scissors'], loses: ['paper']},
scissors: {beat: ['paper'], loses: ['rock']},
paper: {beat: ['rock'], loses: ['scissors']}
}
var getUserChoice = function(text){
var userChoice = prompt(text);
if(userChoice in rules)
return userChoice;
return getUserChoice("Wrong choice, try again! Choose rock, paper or scissors");
};
var getComputerChoice = function(){
return Object.keys(rules)[Math.floor(Math.random() * 3)];
}
var getWinner = function(userChoice, computerChoice){
if(rules[userChoice].beat.indexOf(computerChoice) !== -1)
return 'user';
else if(rules[userChoice].loses.indexOf(computerChoice) !== -1)
return 'computer';
return 'dead heat';
}
var userChoice = getUserChoice("Do you choose rock, paper or scissors?");
var computerChoice = getComputerChoice();
var winner = getWinner(userChoice, computerChoice);
console.log('userChoice=', userChoice, ', computerChoice=', computerChoice, ', winner=', winner);

Categories