Looping a rock-paper-scissors game - javascript

Ok so this should be fairly easy to answer but for some reason im having an issue.( could be because im very new to programming) I've created a rock,papers,scissors game against the CPU. Now i want to ask the user if they want to play again and if they answer Y then it should go through the loop each time. If they type "N" then the game will end. The main issue im having is that once you type in Y to play again it just gives you the result from the last game. Any pointers would help.
Here is what i have :
var userChoice = "";
var userChoice = prompt("Choose rock, paper, or scissors");
var playagain = "Y";
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
choice1 = userChoice;
choice2 = computerChoice;
while (playagain == "Y") {
function compare(choice1, choice2) {
if (choice1 == choice2) {
return ("It's a tie!");
}
if (choice1 == "rock") {
if (choice2 == "scissors") {
return ("You win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "paper") {
if (choice2 == "rock") {
return ("you win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "scissors") {
if (choice2 == "rock") {
return ("computer wins!");
} else {
return ("you win!");
}
}
}
document.write(compare(choice1, choice2));
document.write("<br>");
playagain = prompt("Do you want to play again, Y or N");
userChoice = prompt("Choose rock, paper, or scissors");
}

The only thing you need is to move all game logics under the while loop:
function compare(choice1, choice2) {
if (choice1 == choice2) {
return ("It's a tie!");
}
if (choice1 == "rock") {
if (choice2 == "scissors") {
return ("You win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "paper") {
if (choice2 == "rock") {
return ("you win!");
} else {
return ("computer wins!");
}
}
if (choice1 == "scissors") {
if (choice2 == "rock") {
return ("computer wins!");
} else {
return ("you win!");
}
}
}
}
var playagain = "Y";
while (playagain == "Y") {
var userChoice = prompt("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";
}
document.write(compare(userChoice, computerChoice));
document.write("<br>");
playagain = prompt("Do you want to play again, Y or N");
}
I have:
moved everything except the declaration of playagain into the loop
removed choice1 and choice2 local variables, as they are redundant
removed prompt in the end of the loop, since we have one in the beginning
removed the declaration of an empty userChoice in the beginning
by the advice of #LiYinKing, moved the function out of the loop
Here is the working JSFiddle demo.

Inside of the while loop you need to include your user prompt and new computer generated random number. The problem is your loop is calculating the same random number and user input over and over.

It's hard to explain exactly what's wrong because the code is difficult to follow.
I don't know how you expect the code that sets the computer's choice to run again after the code executes to the bottom of the script.
Declaring named functions in a loop doesn't make sense. Declare them at the top. Then there's nothing left in the body of the loop. Fishy...
What you need is a function that runs the game and a while loop calling that function.
I am on a phone, this is untested
function runGame() {
var userChoice = prompt("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";
}
if(userChoice==computerChoice){
return "It's a tie!";
}
if(userChoice=="rock"){
if(computerChoice=="scissors"){
return "You win!";
} else{
return "computer wins!";
}
}
if(userChoice=="paper"){
if(computerChoice=="rock"){
return "you win!";
} else{
return "computer wins!";
}
}
if(userChoice=="scissors"){
if(computerChoice=="rock"){
return "computer wins!" ;
} else{
return "you win!" ;
}
}
}
alert(runGame());
while ( prompt("Do you want to play again, Y or N") == "Y") {
alert(runGame());
}

Later with experience and knowledge you can write the script like this :
function compare(choice1, choice2) {
if (choice1 == choice2) {
return ("It's a tie!");
}
var lose = {
"rock": "scissors",
"paper": "rock",
"scissors": "paper"
};
return (lose[choice1] == choice2) ? "You win!" : "computer wins!";
}
(function() {
var CHOICE = ["rock", "paper", "scissors"];
var userChoice = "";
var userChoice, computerChoice, playagain, i = 0;
do {
document.write("Ground " + i + " :<br>");
computerChoice = CHOICE[Math.floor(Math.random() * 3)];
do {
userChoice = (""+prompt("Choose rock, paper, or scissors")).toLowerCase();
} while (CHOICE.indexOf(userChoice) === -1);
document.write(userChoice + " vs " + computerChoice + "<br>");
document.write(compare(userChoice, computerChoice) + "<br>");
playagain = (""+prompt("Do you want to play again, Y or N")).toUpperCase();
i++;
} while (["Y", "YES"].indexOf(playagain) !== -1);
});
Explanation :
I add toLowerCase() function to replace "Rock" to "rock", and I add toUpperCase() to replace "y" to "Y".
In this circumstance do { /* script */ } while (bool) is more suitable.
With :
do {
userChoice = (""+prompt("Choose rock, paper, or scissors")).toLowerCase();
} while (CHOICE.indexOf(userChoice) === -1);
You wait a valid answer, three word only : rock or paper or scissors. When userChoice equals "rock" indexOf return 0 ; equals "paper" indexOf return 1...
This syntax :
return (lose[choice1] == choice2) ? "You win!" : "computer wins!";
Is :
if (lose[choice1] == choice2)
return "You win!";
else
return "computer wins!"
JavaScript ternary operator example with functions

Related

use my 1 round code to make a 3 rounds "Rock Paper Scissors" game - Javascript

I'm building a rock paper scissors game with Javascript, i did a 1 round mode of the game and it work, now i want to add a second mode " best of three rounds" but after trying many things i got my code messy and can't figure out what to do exactly.
i try to add a count = 0; count < 3; count = count + 1but don't know exactly where to put it
can someone help me please?
var mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '1') {
oneRound;
}
if (mode === '2') {
bestOfThree;
}
// set Computer Choice
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";
}
// Compare value for oneRound mode
var oneRound = function(computerChoice, userChoice) {
if (computerChoice === userChoice) {
return "The result is tie!";
}
if (computerChoice === "rock") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "paper")
return "Player wins";
}
}
if (computerChoice === "paper") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "rock")
return "Player wins";
}
}
if (computerChoice === "scissors") {
if (userChoice === "rock") {
return "Computer wins";
} else {
if (userChoice === "scissors")
return "Player wins";
}
}
};
console.log("Player Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
console.log(oneRound(computerChoice, userChoice));
Have look at this
I use setTimeout to allow the screen to show the result
const play = () => {
// set Computer Choice
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("Player Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
if (computerChoice === userChoice) {
return "The result is tie!";
}
if (computerChoice === "rock") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "paper")
return "Player wins";
}
}
if (computerChoice === "paper") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "rock")
return "Player wins";
}
}
if (computerChoice === "scissors") {
if (userChoice === "rock") {
return "Computer wins";
} else {
if (userChoice === "scissors")
return "Player wins";
}
}
};
const round = () => {
const res = play();
console.log(res)
cnt--
wins[cnt] = res.startsWith("Player") ? 1 : 0;
if (cnt === 0) {
const total = wins.reduce((a, b) => a + b)
console.log(`You beat the computer ${total} time${total===1?"":"s"}`)
return
}
setTimeout(round, 10) // else go again
}
let cnt = 1,
wins = [];
const mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '2') {
cnt = 3;
}
round()

Rock, paper or scissors game - doesn't return expression of who wins, etc

I made a basic "Rock, paper or scissors" game. I have a few doubts/problems about this project.
On my browser the message of who wins isn't displayed. Such as "Computer wins". What I get is the following:
Computer: Paper
You: rock
And my code is:
let userChoice = prompt("Do you choose Rock, Paper or Scissors?");
let computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Rock";
} else if(computerChoice <= 0.67) {
computerChoice = "Paper";
} else {
computerChoice = "Scissors";
}
let compare = function(choice1, choice2) {
if (choice1 === choice2) {
document.getElementById('printwo').innerHTML = 'The result is a tie!';
}
else if (choice1 === "Rock"){
if (choice2 ==="Scissors") {
document.getElementById('printwo').innerHTML = 'Rock wins';
}
else {
document.getElementById('printwo').innerHTML = 'Paper wins';
}
}
else if (choice1 === 'Paper') {
if (choice2 === 'Rock') {
document.getElementById('printwo').innerHTML = 'Paper wins';
}
else {
document.getElementById('printwo').innerHTML = 'Scissors wins';
}
}
else if (choice1 === 'Scissors') {
if (choice2 ==='Rock') {
document.getElementById('printwo').innerHTML = 'Rock wins';
}
else {
document.getElementById('printwo').innerHTML = 'Scissors wins';
}
}
};
document.getElementById("print").innerHTML = "Computer: " + computerChoice + "</br>" + "You: " + userChoice;
compare(userChoice, computerChoice);
I also wanted to add an else statement to give the message "Please insert a valid response" in case the user doesn't choose any of the 3 options. But where should I place it inside the function? I tried putting it at the end but then it always displayed the message, no matter what I wrote.
Instead of so many else if statements, why can't I write this game using a function which contains many lines of code such as this one:
else if(userChoice === 'Paper' && computerChoice === 'Paper') {
return ('It\'s a tie!'); }
Last but not least, why doesn't it work to use return (instead of document.getElementById()) inside the function and then call the function inside of document.getElementById()
Thanks in advance.
I also wanted to add an else statement to give the message "Please insert a valid response" in case the user doesn't choose any of the 3 options. But where should I place it inside the function? I tried putting it at the end but then it always displayed the message, no matter what I wrote.
This doesn't belong in the compare function.
It will be best when you get the user input.
You might want to repeatedly ask the user until you get a valid input, for example:
const choices = ['Rock', 'Paper', 'Scissors'];
var userChoice;
while (true) {
prompt("Do you choose Rock, Paper or Scissors?");
if (choices.indexOf(userChoice) != -1) break;
console.log('Invalid choice!');
}
By the way, defining the choices also lets you simplify the way you set the computer's choice:
let computerChoice = choices[Math.floor(Math.random() * choices.length)];
Instead of so many else if statements, why can't I write this game using a function which contains many lines of code such as this one:
else if(userChoice === 'Paper' && computerChoice === 'Paper') {
return ('It\'s a tie!'); }
You don't actually have that exact line, thanks to the choice1 === choice2 condition.
In any case, there's nothing fundamentally wrong with having all those if-else-ifs.
You could use a different approach, for example an object oriented one,
where each object would know what other choice beats it and what doesn't,
but it's not so obvious that such approach would be significantly better.
Last but not least, why doesn't it work to use return (instead of document.getElementById()) inside the function and then call the function inside of document.getElementById()
Indeed, it would be better to remove all the repetitive document.getElementById('printwo').innerHTML = from inside the compare function.
You could write like this instead:
let compare = function(choice1, choice2) {
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 (choice2 === 'Rock') {
return 'Rock wins';
} else {
return 'Scissors wins';
}
}
};
document.getElementById('printwo').innerHTML = compare(userChoice, computerChoice);
A more compact writing style is possible with using the ternary operator ?::
if (choice1 === choice2) {
return 'The result is a tie!';
} else if (choice1 === "Rock") {
return choice2 === "Scissors" ? 'Rock wins' : 'Paper wins';
} else if (choice1 === 'Paper') {
return choice2 === "Rock" ? 'Paper wins' : 'Scissors wins';
} else {
return choice2 === "Rock" ? 'Rock wins' : 'Scissors wins';
}
Here's an alternative data-driven approach:
const rps = {
rock: {
paper: 'Paper wins',
scissors: 'Rock wins'
},
paper: {
rock: 'Paper wins',
scissors: 'Scissors wins'
},
scissors: {
rock: 'Rock wins',
paper: 'Scissors wins'
}
};
let compare = function(choice1, choice2) {
if (choice1 === choice2) {
return 'The result is a tie!';
}
return rps[choice1.toLowerCase()][choice2.toLowerCase()];
};

Some trouble in javascript While using If/else

I am learning JavaScript through Codecademy. There I was asked to make a rock paper and scissor game. I did it by coding the following:
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) {
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"
}
};
};
compare(userChoice, computerChoice);
but later I myself added a code to stop unavailable choices like if any one choosed "egg"
var a = function() {
if (userchoice !== "scissors") {
if (userChoice !== "rock") {
if (userChoice !== "paper") {
console.log "unavilable"
};
};
};
};
to check I typed "dog" but it didn't display"unavailable"
console.log "unavilable"
should be
console.log("unavilable")
Also you need to call the function a:
compare(userChoice, computerChoice);
a();
Update:
if (userchoice !== "scissors") { //Problem is here "userChoice" and not "userchoice"
See the fiddle.
It would be better to concat the conditions
if(userchoice!="..." && userchoice!="...")
console.log(...)
or even use
switch(userchoice)
case: "rock":
case: "paper":
console.log(...);
break;
You have mistyped userChoice with userchoice.
I would recommend you to implement a method inArray. The code will be more readable this way. Here is the code for it:
function inArray(needle, haystack){
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
Then you are just calling it in your code. Here is a jsFiddle with the complete code: jsFiddle.net

How would you make the result print "computer wins" or "user wins"

Obviously, this will print out rock/paper/scissors wins or it's a tie.
What is the best way to achieve a result like "Rock beats scissors -- Computer wins!" and such?
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) {
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 === "paper") {
return "scissors wins";
} else {
return "rock wins";
}
}
}
compare(userChoice,computerChoice);
I have some knowledge of functions and variables that I think is enough to solve this -- I just can't figure it out. I have less than 8 hours of javascript experience.
Also, this is not my homework, I just finished a lesson in codecademy and wondered this.
I would look into changing the strings in the program so instead of just "scissors wins" I would change that to "Scissors beats (insert corresponding choice here) - Player wins!!!"
You can find the corresponding choice by trial and error debugging or by following the logic of the nested if's and else's.
Hope this helps ;)
Here is a simple way to do it by appending to the DOM.
This example uses a do {} while () loop to keep asking the player if he wants to play, and if so asks for his choice. It then displays the result (tie or player / cpu wins) to the output element on the page. This method is nice because it keeps track of the plays for you, so if you need to do a "best 3 of 5" you can see who ultimately wins!
jQuery jsFiddle example: http://jsfiddle.net/edahqpho/3/
Pure javascript jsFiddle example: http://jsfiddle.net/edahqpho/1/
HTML
<div id='output'></div>
Javascript (pure JS example)
function play() {
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);
return compare(userChoice, computerChoice);
}
var compare = function (choice1, choice2) {
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 === "paper") {
return "scissors wins";
} else {
return "rock wins";
}
}
}
var output = document.getElementById('output');
do {
var result = play();
var display = document.createElement("DIV");
var text = document.createTextNode(result);
display.appendChild(text);
output.appendChild(display);
}
while (window.confirm("Play again?"));
This next snippet demonstrates a more advanced visualization of the game using similar DOM injecting techniques (which are waaaay easier with a library like jQuery).
function play() {
do {
var userChoice = prompt("Do you choose rock, paper or scissors?").toLowerCase();
} while (userChoice != "rock" && userChoice != "paper" && userChoice != "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 playResult = {
User: userChoice,
CPU: computerChoice,
Winner: compare(userChoice, computerChoice)
};
return playResult;
}
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "tie";
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "player";
} else {
return "cpu";
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
return "player";
} else {
return "cpu";
}
} else if (choice1 === "scissors") {
if (choice2 === "paper") {
return "player";
} else {
return "cpu";
}
}
}
function getIcon(shape) {
var url = "";
switch (shape) {
case "paper":
url = "http://megaicons.net/static/img/icons_sizes/8/178/256/rock-paper-scissors-paper-icon.png";
break;
case "rock":
url = "http://megaicons.net/static/img/icons_sizes/8/178/256/rock-paper-scissors-rock-icon.png";
break;
case "scissors":
url = "http://megaicons.net/static/img/icons_sizes/8/178/256/rock-paper-scissors-scissors-icon.png";
break;
}
return url;
}
function game() {
var $output = $("#output");
var result = play();
$output.append("<tr><td><img src='" + getIcon(result.User) + "'/></td><td><img src='" + getIcon(result.CPU) + "'/></td><td>" + result.Winner.toUpperCase() + "</td></tr>");
setTimeout(function () {
if (window.confirm("Play again?")) {
game()
}
}, 10);
}
// start the game of all games...
game();
#output th, #output td {
margin: 10px;
padding: 10px;
font-size: 14px;
font-family:"Segoe UI", Arial, "Sans serif";
}
img {
width: 20px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='output'>
<tr>
<th>Player</th>
<th>CPU</th>
<th>Winner</th>
</tr>
</table>

How to make it so only valid options can be chosen for rock paper scissors

Ive made a small Rock paper scissor game with javascript. There are two things that I would like to do to make the game a little better.
1) If the player gives an answer other than rock, paper or scissors for a prompt saying "Please pick between one of the three options: rock, paper or scissors"
I have implemented something like this but it only goes one run. I would like to have the prompt come up until one of the three answers is given
2) I would like to have the game start running code from the top again if it is a tie. How could I get the program to start from the top again?
Here is the code
var userChoice = prompt("Do you choose rock, paper or scissors?");
if (userChoice === "rock")
{}
else if (userChoice === "paper"){}
else if (userChoice === "scissors"){}
else {
userChoice = prompt ("Please pick between one of the three options: 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( "The computer's choice is" + " " + computerChoice);
console.log("Your choice was " + userChoice);
var compare = function(choice1 , choice2)
{
if (choice1 === choice2)
{
return "The result is a tie!";
}
if (choice1 === "rock")
{
if (choice2 === "scissors")
{
return "rock wins";
}
else
{
return "paper wins";
}
}
if (choice1 === "paper")
{
if (choice2 === "rock")
{
return "paper wins";
}
else
{
return "scissors wins";
}
}
if (choice1 === "scissors")
{
if (choice2 === "rock")
{
return "rock wins";
}
else
{
return "scissors wins";
}
}
};
compare(userChoice, computerChoice);
What you are doing in this program is only 'Conditional statement' checking. There is another construct to Structured Programming that is called 'Loops'
Generally it is humanly possible to copy-paste a segment of code 1000s of times and maybe even millions but not infinite. So for such cases programmers use Loops that start with an initial state, execute the same body of code as long as a given condition holds and follows a state change.
You can use a while loop in this case as it is the simplest structure for such scenarios. It only takes the 'condition' for which it much keep executing the body of code. The structure of while loop is as such.
while ( condition ) {
<the code that you want it to keep executing>
}
If we break your program down into various parts there are mainly 2 parts to it.
1. Take the input
2. Check if the input is valid or not. If not take the input again.
From this you can easily see what should be the condition for your loop.
"While the input is not valid"
So it's like
while ( the input is not valid / the userChoice is not rock or paper or scissors ) {
take the input
}
To make your loop infinite you can use
while ( true ) {
take the input
}
To break out of this infinite loop, you use "break;" anywhere inside it. So a 'break;' inside an if statement will get out of this loop like this
while ( true ) {
if ( condition ) {
break;
}
}
So, if we follow your style of condition checks we get.
var userChoice = prompt("Do you choose rock, paper or scissors?");
while ( true ) {
if (userChoice === "rock")
{break;}
else if (userChoice === "paper"){break;}
else if (userChoice === "scissors"){break;}
else {
userChoice = prompt ("Please pick between one of the three options: rock, paper or scissors");
}
}
But using 'breaks' is a bad programming practice. So why don't we take the advantage of while's 'condition'?
var userChoice = prompt("Do you choose rock, paper or scissors?");
while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
userChoice = prompt("Please pick between one of the three options: rock, paper or scissors");
}
And since you want the Game to go on forever, we can put the whole game inside a loop right? But that will totally take your control off your browser and you can't do anything while that loop is waiting for your response. So we keep a way out for ourselves? Why don't we add another condition that, if the user types "EXIT" the game stops?
while ( true ) {
var userChoice = prompt("Do you choose rock, paper or scissors?");
while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" && userChoice !== "EXIT") {
userChoice = prompt("Please pick between one of the three options: rock, paper or scissors");
}
if (userChoice === "EXIT") {
console.log("Thanks for playing :)");
break;
}
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log( "The computer's choice is" + " " + computerChoice);
console.log("Your choice was " + userChoice);
var compare = function(choice1 , choice2)
{
if (choice1 === choice2)
{
return "The result is a tie!";
}
if (choice1 === "rock")
{
if (choice2 === "scissors")
{
return "rock wins";
}
else
{
return "paper wins";
}
}
if (choice1 === "paper")
{
if (choice2 === "rock")
{
return "paper wins";
}
else
{
return "scissors wins";
}
}
if (choice1 === "scissors")
{
if (choice2 === "rock")
{
return "rock wins";
}
else
{
return "scissors wins";
}
}
};
compare(userChoice, computerChoice);
}
Now, you can make this much easier to Modify later (for you and others) by breaking your program down into functions just the way you did for the Compare part. Then taking the decision on the userInput will be much more robust process.
function take_user_input() {
var userChoice = prompt("Do you choose rock, paper or scissors?");
while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" && userChoice !== "EXIT") {
userChoice = prompt("Please pick between one of the three options: rock, paper or scissors");
}
return userChoice;
}
function play(userChoice) {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log( "The computer's choice is" + " " + computerChoice);
console.log("Your choice was " + userChoice);
var compare = function(choice1 , choice2)
{
if (choice1 === choice2)
{
return "The result is a tie!";
}
if (choice1 === "rock")
{
if (choice2 === "scissors")
{
return "rock wins";
}
else
{
return "paper wins";
}
}
if (choice1 === "paper")
{
if (choice2 === "rock")
{
return "paper wins";
}
else
{
return "scissors wins";
}
}
if (choice1 === "scissors")
{
if (choice2 === "rock")
{
return "rock wins";
}
else
{
return "scissors wins";
}
}
};
compare(userChoice, computerChoice);
}
while ( true ) {
var userChoice = take_user_input();
if (userChoice === "EXIT") {
console.log("Thanks for playing :)");
break;
} else {
play(userChoice);
}
}
And after that, you can study more on reading DOM elements and modifying them using jQuery / modifying the HTML by Javascript. :) But that brings a totally new topic. But I'd suggest you to look that way. Nobody would love to play Rock Paper Scissors using Console Log when they can do that using Graphical User Interface.
You could wrap the game in a function, which you then call at any point. Maybe put the initial prompt in its own function, if its valid, call the game function.
function getUserInput()
{
// put prompt and validation logic here, then call when its a tie
// You might try consolidating the validation logic with regular expression:
// This returns an array of matches if only rock, paper or scissors was entered.
userChoice.match(/(rock|paper|scissors)/)
if(userChoice)
{
runGameLogic();
}
}

Categories