Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jimmy Mannan
5,201 PointsHow to add score?
Below is the code: its long and messy but I am still learning. My question is: After each turn I have to refresh for another turn. How do I keep playing or maybe keep playing for 5-10 turns and the score keeps adding. Now when I refresh, score again is zero and starts again.
I will really apreciate if the solution is also beginner level so I can understand and follow.
var userChoice = prompt("Do you choose rock, paper or scissors?").toUpperCase();
var Rayaan_Score = 0;
var Comp_Score = 0;
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock".toUpperCase();
} else if(computerChoice <= 0.67) {
computerChoice = "paper".toUpperCase();
} else {
computerChoice = "scissors".toUpperCase();
}
var compare = function(choice1,choice2) {
if (choice1 === choice2) {
alert("Comp choice: " + computerChoice);
document.write("<h2>Uh Oh!!!No one wins...both are same</h2>");
userChoice = prompt("Choose again rock, paper or scissors?").toUpperCase();
}
else if (choice1 === "ROCK") {
if (choice2 === "SCISSORS") {
alert("Comp choice: " + computerChoice);
document.write("<h2>Rock broke the Scissors hahaha!!<h2>");
Rayaan_Score +=1;
}
else {
alert("Comp choice: " + computerChoice);
document.write("<h2>Paper covered the Rock!! HAHAHA</h2>");
Comp_Score +=1;
}
}
else if (choice1 === "PAPER") {
if (choice2 === "ROCK") {
alert("Comp choice: " + computerChoice);
document.write("<h2>Paper covered the Rock!! HAHAHA</h2>");
Rayaan_Score +=1;
}
else {
alert("Comp choice: " + computerChoice);
document.write("<h2>Scissors cut the Paper in small pieces!! hahaha!!</h2>");
Comp_Score +=1;
}
}
else if (choice1 === "SCISSORS") {
if (choice2 === "ROCK") {
alert("Comp choice: " + computerChoice);
document.write("<h2>Rock broke the Scissors!! hahaha!!</h2>");
Comp_Score +=1;
}
else {
alert("Comp choice: " + computerChoice);
document.write("<h2>Scissors cut the Paper in small pieces!! hahaha!!</h2>");
Rayaan_Score +=1;
}
}
else {
alert("You have made an invalid choice, Monkey Boy!!");
}
};
compare(userChoice, computerChoice);
document.write("<p>Rayaan's Score: " + Rayaan_Score);
document.write("<p>Comp: " + Comp_Score);
Thanks jimmy
2 Answers
Dane Parchment
Treehouse Moderator 11,077 PointsHere is my code, I have rewritten your code to be a bit more modular with more functions for added flexibility and less if statements, so that it can be changed and customized to your liking.
var playerScore = 0;
var computerScore = 0;
function welcomeMessage() {
alert("Welcome the good ol' fashion game of Rock, Paper, Scissors! Remember the rules are simple!\nRock Beats Scissors\nScissors Beats Paper\nPaper Beats Rock");
}
function playGame(numOfRounds) {
welcomeMessage();
do {
var player = playerGuess();
var computer = computerGuess();
var result = compareGuesses(player, computer);
updateScores(result, 5);
if(result !== 0) {
numOfRounds--;
}
}while(numOfRounds > 0);
if(playerScore > computerScore) {
alert("The player has " + playerScore + " points compared to the computer's " + computerScore + " points. So the player wins!");
}
else {
alert("The computer has " + computerScore + " points compared to the player's " + playerScore + " points. So the computer wins!");
}
clearScores();
}
function playerGuess() {
var playerChoice = prompt("Choose rock, paper, or scissors.");
if(playerChoice === "rock" || playerChoice === "paper" || playerChoice === "scissors") {
alert("Good job");
return playerChoice;
}
alert("You typed something else or did not spell your choice correctly please try again!");
playerGuess();
}
function computerGuess() {
var choice = Math.random();
if(choice < 0.34) {
return "rock";
}
if(choice <= 0.67) {
return "paper";
}
return "scissors";
}
function compareGuesses(guess1, guess2) {
//Create an alert message detailing the results
alert("Player chose: " + guess1 + " and the computer chose: " + guess2 + "!");
//First check for equality
if(guess1 === guess2) {
alert("You and the computer guessed the same thing! Go again, no score added!");
return 0;
}
//No check for guess1 winning
if(
(guess1 === "rock" && guess2 === "scissors")
||
(guess1 === "paper" && guess2 === "rock")
||
(guess1 === "scissors" && guess2 === "paper"))
{
alert("Player wins the round!");
return 1;
}
alert("Computer wins the round!");
return 2;
}
function updateScores(result, points) {
if(result === 1) {
playerScore += points;
}
if(result === 2) {
computerScore += points;
}
if(result === 0) {
computerScore += 0;
playerScore += 0;
}
}
function clearScores() {
playerScore = 0;
computerScore = 0;
}
playGame(3);
I will now go more in deph about what I did and why I made certain changes, so then let's start with the variables. Basically we have two variables that we now have to keep track of, the player score and the computer score, so let's initiate these to zero. That's all we have to do, the script will take care of the rest.
var playerScore = 0;
var computerScore = 0;
Now let's look at the welcome message function. To be honest, you could have just made this a variable and alerted this out, it doesn't need to be in a function. But i placed it in there if you wanted to call the welcome message at any time in the program without having to keep track of an extra variable.
function welcomeMessage() {
alert("Welcome the good ol' fashion game of Rock, Paper, Scissors! Remember the rules are simple!\nRock Beats Scissors\nScissors Beats Paper\nPaper Beats Rock");
}
We are going to skip the playGame method for now and move onto the playerGuess function. What I decided to do here was just make a prompt where the player will enter their choice, if that choice is rock, paper, or scissors then return that choice, otherwise let the player know they messed up and let them try again (if you follow programming methods, a method that refers to itself is commonly known as a recursive function/method).
function playerGuess() {
var playerChoice = prompt("Choose rock, paper, or scissors.");
if(playerChoice === "rock" || playerChoice === "paper" || playerChoice === "scissors") {
alert("Good job");
return playerChoice;
}
alert("You typed something else or did not spell your choice correctly please try again!");
playerGuess();
}
Next we will create the computerGuess function, this one is a bit different than yours but it follows the same idea as yours. Basically the computer will pick a random number between 0 and 1 if it is below .34 the return rock, if it below or equal to .67 return paper, and for all other numbers return scissors.
function computerGuess() {
var choice = Math.random();
if(choice < 0.34) {
return "rock";
}
if(choice <= 0.67) {
return "paper";
}
return "scissors";
}
Now we will look at the compareGuesses method, this one is probably the most verbose method and differs greatly from yours. Basically we look at two parameters and check if they are equal to each if they are return the number 0, this means tie. If any of the player's guesses beat the computer's guess than return a 1 which means the player won. Finally if the guesses are not tied and the player did not beat the computer's guess, then the computer wins. I opted to return numbers instead of strings so that in the update score function life would be a bit easier for me. You can use whatever approach you see fit.
function compareGuesses(guess1, guess2) {
//Create an alert message detailing the results
alert("Player chose: " + guess1 + " and the computer chose: " + guess2 + "!");
//First check for equality
if(guess1 === guess2) {
alert("You and the computer guessed the same thing! Go again, no score added!");
return 0;
}
//No check for guess1 winning
if(
(guess1 === "rock" && guess2 === "scissors")
||
(guess1 === "paper" && guess2 === "rock")
||
(guess1 === "scissors" && guess2 === "paper"))
{
alert("Player wins the round!");
return 1;
}
alert("Computer wins the round!");
return 2;
}
In the updateScores function we will actually update the player's or the computer scores by a set amount based on the parameter points, this allows you to custom tailor how many points you get for winning a round. The other parameter, results, will be that of the returned value of the compareGuesses method, this allows us to quickly see who needs to have their score updated without having to compare strings again or use a lot of nested if statements. So if the result is one update the player's score by the points, if the result is 2 update the computers, and if it is 0 update neither, its a tie.
function updateScores(result, points) {
if(result === 1) {
playerScore += points;
}
if(result === 2) {
computerScore += points;
}
if(result === 0) {
computerScore += 0;
playerScore += 0;
}
}
Now we have the clearScores function and if this wasn't obvious already all it does is clear the scores. Now that we have that out of the way time to move on the the main function of this script.
function clearScores() {
playerScore = 0;
computerScore = 0;
}
Finally the playGame function allows us to actually play the game and is in charge of looping through the rounds and keeping track of and eventually clearing the scores. I didn't do it here but you would also display the results to the website using html here as well. So let's break down how this works. First the function takes a parameter called rounds, this will determine how many round the game plays out, you can set this yourself. Next we display the welcome message. Finally we move on the the loop, I chose to use a do while loop because it makes sense to me, run the game once, and then keep running it again based on the rounds left. Of course you can use a for loop or a while loop here it really doesn't matter. within the loop I set a variable equal to result of the playerGuess method and do the same for both the computerGuess and the compareGuesses functions. I then update the scores. Now if the result is not a tie then decrease the round by one, otherwise run the round again, we have a tie to break. the loop itself will run until the numOfRounds becomes 0. Once the loop is complete we alert who won the game and their score compared to the looser's. And that's it, that's the program, pretty easy right?!
function playGame(numOfRounds) {
welcomeMessage();
do {
var player = playerGuess();
var computer = computerGuess();
var result = compareGuesses(player, computer);
updateScores(result, 5);
if(result !== 0) {
numOfRounds--;
}
}while(numOfRounds > 0);
if(playerScore > computerScore) {
alert("The player has " + playerScore + " points compared to the computer's " + computerScore + " points. So the player wins!");
}
else {
alert("The computer has " + computerScore + " points compared to the player's " + playerScore + " points. So the computer wins!");
}
clearScores();
}
Of course there are a few bugs, I just slapped this together really quick, for example when the player types something in wrong, they get to go again, but their new result is documented as undefined and the computer gets a win. These bugs are minor though and can easily be fixed by you! Thanks for taking the time to read my answer.
John Deininger
3,958 PointsThere is a course on JavaScript loops that will probably help you out.
Jimmy Mannan
5,201 PointsThank you John for the tip
Jimmy Mannan
5,201 PointsJimmy Mannan
5,201 PointsThanks a lot Dane for taking the time the explain all the steps in detail. And there doesnt seem to be any bugs either. It ran fine when I played it.
It seems like a good idea to have more functions than if/else, guess I should practice functions more :-) to become more familiar.
Thanks again jimmy