How to continue gameplay without page reload - javascript

I am building a Javascript Rock, Paper, Scissors game and I have to reload the page every time I want to play another "round". Any suggestions on how to continue looping through the game without reloading the page and keeping the score?
var compChoice = "";
var userChoice = "";
//comp choice
compChoice = Math.random();
if(compChoice < 0.34) {
compChoice = 'rock';
}
else if(compChoice <= 0.67) {
compChoice = 'paper';
}
else {
compChoice = 'scissors';
};
//compare function
var compare = function(userChoice, compChoice) {
if(userChoice == compChoice) {
return("Draw");
}
else if(userChoice == "rock" && compChoice == "scissors") {
return("PLayer Wins");
}
else if (userChoice == "paper" && compChoice == "rock") {
return("Player Wins");
}
else if (userChoice == "scissors" && compChoice == "paper") {
return("Player Wins");
}
else {
return("Player loses");
}
};
//click events
$('#rock').click(function() {
var result = compare('rock', compChoice);
$('#decision').html(result);
})
$('#paper').click(function() {
var result = compare('paper', compChoice);
$('#decision').html(result);
})
$('#scissors').click(function() {
var result = compare('scissors', compChoice);
$('#decision').html(result);
})

If you turn the computers choice into a function which returns the value you can then call it every time and get a new value.
var userChoice = "";
//comp choice
var getCompChoice = function() {
var choice = Math.random();
if(choice < 0.34) {
return 'rock';
}
else if(choice <= 0.67) {
return 'paper';
}
else {
return 'scissors';
}
}
//compare function
var compare = function(userChoice) {
compChoice = getCompChoice();
if(userChoice == compChoice) {
return("Draw");
}
else if(userChoice == "rock" && compChoice == "scissors") {
return(`Player Wins. rock > ${compChoice}`);
}
else if (userChoice == "paper" && compChoice == "rock") {
return(`Player Wins. paper > ${compChoice}`);
}
else if (userChoice == "scissors" && compChoice == "paper") {
return(`Player Wins. scissors > ${compChoice}`);
}
else {
return(`Player Looses. ${userChoice} < ${compChoice}`);
}
};
//click events
$('#rock').click(function() {
var result = compare('rock');
$('#decision').html(result);
})
$('#paper').click(function() {
var result = compare('paper');
$('#decision').html(result);
})
$('#scissors').click(function() {
var result = compare('scissors');
$('#decision').html(result);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rock">rock</div>
<div id="scissors">scissors</div>
<div id="paper">paper</div>
<div id="decision"></div>

I've made a fiddle for you: https://jsfiddle.net/9uq19dtc/1/.
Basically you just needed to put your compChoice code in a place where it gets called for every button click, rather than only when the page loads.
To keep score, just make 2 more divs that have player score and comp score, and increment their values each time one of them wins.

Have your 'click' buttons do the compChoice logic instead of at the beginning, so it chooses a new result whenever you click Rock, Paper, or Scissors:
var userChoice = "";
//comp choice
var chooseCompChoice = function() {
compChoice = Math.random();
if(compChoice < 0.34) {
return 'rock';
}
else if(compChoice <= 0.67) {
return 'paper';
}
else {
return 'scissors';
}
};
//compare function
var compare = function(userChoice, compChoice) {
if(userChoice === compChoice) {
return("Draw");
}
else if(userChoice === "rock" && compChoice === "scissors") {
return("Player Wins");
}
else if (userChoice === "paper" && compChoice === "rock") {
return("Player Wins");
}
else if (userChoice === "scissors" && compChoice === "paper") {
return("Player Wins");
}
else {
return("Player loses");
}
};
//click events
$('#rock').click(function() {
var compChoice = chooseCompChoice();
var result = compare('rock', compChoice);
$('#decision').html(result);
})
$('#paper').click(function() {
var compChoice = chooseCompChoice();
var result = compare('paper', compChoice);
$('#decision').html(result);
})
$('#scissors').click(function() {
var compChoice = chooseCompChoice();
var result = compare('scissors', compChoice);
$('#decision').html(result);
})

Related

Conditional statement returns same result regardless of outcome

I'm trying to manipulating the DOM to show who wins when playing Rock paper scissors game. I'm targeting a <p class="result" to do this. But it doesn't matter what the result is, "it's a Draw" is only displayed. Please help!
On a side note, if any one has any suggestions on how to refactor this due to the multiple lines of "player wins", "Computer wins" code, then please let me know.
for (var i = 0; i < document.querySelectorAll("button").length; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
var playerChoice = (this.innerHTML);
var random = Math.floor(Math.random() * document.querySelectorAll("button").length);
var compChoice = ["Rock", "Paper", "Scissors"]
document.querySelector(".player").innerHTML = playerChoice;
document.querySelector(".computer").innerHTML = compChoice[random]
if (playerChoice === "Rock" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Paper" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Paper" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Rock" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === compChoice) {
document.querySelector(".result").innerHTML = "It's a draw";
}
console.log(playerChoice);
})
}
https://ibb.co/44Z1vQ3
Brandom's idea in the comments above to console.log playerChoice helped me realise a way to problem solve this by also console logging compchoice which returns an array, so i needed to encapsulate the compChoice[random] into a variable first shown below.
It is now all working as it should.
for (var i = 0; i < document.querySelectorAll("button").length; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
var playerChoice = (this.innerHTML);
var random = Math.floor(Math.random() * document.querySelectorAll("button").length);
var choices = ["Rock", "Paper", "Scissors"]
var compChoice = choices[random]
document.querySelector(".player").innerHTML = playerChoice;
document.querySelector(".computer").innerHTML = compChoice;
if (playerChoice === "Rock" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Paper" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Player Wins.";
} else if (playerChoice === "Scissors" && compChoice === "Rock") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Paper" && compChoice === "Scissors") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === "Rock" && compChoice === "Paper") {
document.querySelector(".result").innerHTML = "Computer Wins.";
} else if (playerChoice === compChoice) {
document.querySelector(".result").innerHTML = "It's a draw";
}
console.log(playerChoice);
console.log(compChoice);
})
}

Rock, paper, scissors game - repeating for 5 rounds

I am building the rock, paper scissors task. At the minute my code only works for 1 round. I'm unsure about how I would get this to keep the score, whilst repeating for 5 rounds. I'm under the impression i will need a for loop at least for the rounds, along the lines of:
for(i=0; i<5;i++);
but i don't know where to slot it into my code. I've looked around online, and i cant find a simple enough to understand resource that doesn't start using switch methods or any other more advanced code to build the game. Any help would be appreciated. Thanks.
function computerPlay() {
let random = Math.random();
if (random <= 0.3333) {
return "paper";
} else if (random >= 0.6666) {
return "rock";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
computerScore++;
return lose;
} else if (computerSelection === "rock") {
return tie;
} else {
userScore++;
return win;
}
}
if (playerSelection.toLowerCase() === "scissors") {
if (computerSelection === "paper") {
userScore++;
return win;
} else if (computerSelection === "rock") {
computerScore++;
return lose;
} else {
return tie;
}
}
if (playerSelection.toLowerCase() === "paper") {
if (computerSelection === "paper") {
return tie;
} else if (computerSelection === "rock") {
userScore++;
return win;
} else {
computerScore++;
return lose;
}
}
}
let userScore = parseInt(0);
let computerScore = parseInt(0);
let win = "You win"
let lose = "You lose"
let tie = "It is a tie"
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
I have edited your code snipet little bit hope it will fulfill your need :)
just put below code into the for loop
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
function computerPlay() {
let random = Math.random();
if (random <= 0.3333) {
return "paper";
} else if (random >= 0.6666) {
return "rock";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
computerScore++;
return lose;
} else if (computerSelection === "rock") {
return tie;
} else {
userScore++;
return win;
}
}
if (playerSelection.toLowerCase() === "scissors") {
if (computerSelection === "paper") {
userScore++;
return win;
} else if (computerSelection === "rock") {
computerScore++;
return lose;
} else {
return tie;
}
}
if (playerSelection.toLowerCase() === "paper") {
if (computerSelection === "paper") {
return tie;
} else if (computerSelection === "rock") {
userScore++;
return win;
} else {
computerScore++;
return lose;
}
}
}
let userScore = parseInt(0);
let computerScore = parseInt(0);
let win = "You win"
let lose = "You lose"
let tie = "It is a tie"
for(var i=0;i<5;i++){
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
}
Try below code:
Looping is not a good approach, read here:
Recursion vs loops
https://www.refactoring.com/catalog/replaceIterationWithRecursion.html
It allows the user to play for 5 times.
Using recursion:
function computerPlay() {
let random = Math.random();
if (random <= 0.3333) {
return "paper";
} else if (random >= 0.6666) {
return "rock";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
computerScore++;
return lose;
} else if (computerSelection === "rock") {
return tie;
} else {
userScore++;
return win;
}
}
if (playerSelection.toLowerCase() === "scissors") {
if (computerSelection === "paper") {
userScore++;
return win;
} else if (computerSelection === "rock") {
computerScore++;
return lose;
} else {
return tie;
}
}
if (playerSelection.toLowerCase() === "paper") {
if (computerSelection === "paper") {
return tie;
} else if (computerSelection === "rock") {
userScore++;
return win;
} else {
computerScore++;
return lose;
}
}
}
let userScore = parseInt(0);
let computerScore = parseInt(0);
let win = "You win"
let lose = "You lose"
let tie = "It is a tie"
var i = 0;
const play = () => {
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
i++;
if (i !== 5) {
play();
} else {
alert("Game Over=> User("+userScore+") vs Computer("+computerScore+")");
}
}
play();

Why is this console.log() failing?

I am creating Rock Paper Scissors for a class, and I'm trying to get it to log the winner in the console, but nothing happens when the button is pressed. I'm not sure why. Is there anything obviously wrong with my code here?
let playGame = function() {
let userChoice = prompt("Do you choose rock, paper or scissors?");
let computerChoice = Math.random();
let userWins = 0;
let compWins = 0;
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67 && computerChoice >= 0.34) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
let compare = function(choice1, choice2) {
if (choice1 === choice2) {
console.log("The result is a tie!");
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
console.log("User wins!");
} else {
console.log("Computer wins!");
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
console.log("User wins!");
} else {
console.log("Computer wins!");
}
} else if (choice1 === "scissors") {
if (choice2 === "paper") {
console.log("User wins!");
} else {
console.log("Computer wins!");
}
}
};
compare(userChoice, computerChoice);
}
<button class="playGame" onclick="playGame()">Play!</button>

Newbie Javascript function returning undefined, rock paper scissors game

As a newbie, following the code academy course, I've come across a problem building a rock paper scissors game.
I've created 2 functions which contain the whole program, the program runs fine when the 2 choices are different but it returns undefined when the choices are the same and I can't understand why.
I can see that when the choices are tied, new choices keep being assigned until they are different and then the compare function is called on these different choices, which should return a winning result.
Just to add, I'd like to fix the code as it is, not rewrite the entire thing, I've completed this exercise on codeacademy but I'm just trying to do it in a different way as 2 self contained functions.
Thanks
var makeChoices = function() {
userChoice = "";
computerChoice = "";
userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice + " " + "User: " + userChoice);
};
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
makeChoices();
compare(userChoice, computerChoice);
}
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";
}
}
else {
return "invalid choice by user";
}
};
makeChoices();
compare (userChoice, computerChoice);
You have to return the result of the recursive call. Try changing
...
compare(userChoice, computerChoice);
...
to
...
return compare(userChoice, computerChoice);
...
When it is equal, you have "compare(userChoice, computerChoice);". The variables userChoice and computerChoice were defined in the makeChoices() function. They won't be available in compare() function. You can make them as global variables or consider moving you the compare() function calls to the bottom of makeChoices().
We all start the same way this impressive language!, do not worry about being a novice, you will soon be a teacher if you do not surrender!,here is the complete code for this exercise below:
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";
}
var compare = function(computerChoice, userChoice) {
if (computerChoice===userChoice) {
return("The result is a tie!");
}
if (userChoice === "rock"){
if (computerChoice === "paper") {
return("paper wins");
}
else if (computerChoice === "scissors") {
return("rock wins");
}
}
if (userChoice === "scissors") {
if (computerChoice==="paper") {
return("scissors wins");
}
else if (computerChoice === "rock") {
return("rock wins");
}
}
if (userChoice === "rock") {
if (computerChoice==="scissors") {
return "rock wins";
}
else if (computerChoice=== "paper") {
return "paper wins";
}
}
if (userChoice === "paper") {
if (computerChoice ==="scissors") {
return "scissors wins";
}
else if (computerChoice==="rock") {
return "paper wins";
}
}
};
compare();
I made such a game before:
var prsStatements = {
paperBeatsRock: 'Paper Beats Rock',
rockBeatsScissors: 'Rock Beats Scissors',
scissorsBeatsPaper: 'Scissors Beats Paper',
seperator: ' - ',
player1: 'Player One',
player2: 'Player Two',
wins: ' Wins!',
tie: "It's a Tie!",
tally: 'Final Tally: '
}
function PaperRockScissors(player1, player2){
var p = /^paper$/i, r = /^rock$/i, s = /^scissors$/i, prss = prsStatements, sep = prss.seperator, win = prss.wins;
var pbr = prss.paperBeatsRock+sep, rbs = prss.rockBeatsScissors+sep, sbp = prss.scissorsBeatsPaper+sep;
var plr1 = player1 ? player1 : prss.player1;
var plr2 = player2 ? player2 : prss.player2;
var p1w = plr1+win, p2w = plr2+win;
this.p1 = 0; this.p2 = 0;
this.rand = function(){
switch(Math.floor(Math.random()*3)){
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
this.play = function(in1, in2){
var i2 = in2 || this.rand();
if(in1.match(p) && i2.match(r)){
++this.p1;
return pbr+p1w;
}
else if(i2.match(p) && in1.match(r)){
++this.p2;
return pbr+p2w;
}
else if(in1.match(r) && i2.match(s)){
++this.p1;
return rbs+p1w;
}
else if(i2.match(r) && in1.match(s)){
++this.p2;
return rbs+p2w;
}
else if(in1.match(s) && i2.match(p)){
++this.p1;
return sbp+p1w;
}
else if(i2.match(s) && in1.match(p)){
++this.p2;
return sbp+p2w;
}
else if(in1.match(i2r)){
return prss.tie;
}
else{
return this;
}
}
this.tally = function(){
var pt = prss.tally;
if(this.p1 > this.p2){
return pt+p1w;
}
else if(this.p2 > this.p1){
return pt+p2w;
}
else{
return pt+prss.tie;
}
}
}
var pr = new PaperRockScissors('Joe', 'Bob');
console.log(pr.play('paper', 'rock'));
console.log(pr.play('rock', 'Paper'));
console.log(pr.play('scissors', 'paper'));
console.log(pr.play('rock', 'Paper'));
console.log(pr.play('paper', 'rock'));
console.log(pr.play('Paper', 'Scissors'));
console.log(pr.play('Paper', 'paper'));
console.log(pr.play('paper', 'Rock'));
console.log(pr.tally());
If you want to make this web-functional you would simply pass user input values, like:
pr.play(someElement.value, anotherElement.value);
Of course, you would want to use an Event and pass the correct values of either 'paper', 'rock', or 'scissors'.
Computer play might look like:
var pc = new PaperRockScissors('Joe', 'Comupter');
console.log(pc.play('paper'));
console.log(pc.play('rock'));
console.log(pc.play('scissors'));
console.log(pc.play('rock'));
console.log(pc.play('paper'));
console.log(pc.play('Paper'));
console.log(pc.play('Paper'));
console.log(pc.play('paper'));
console.log(pc.tally());

Run outside variable from inside a function

if result is tie i need to run this code again by asling "Do you choose rock, paper or scissors?"
but there's a wrong with this code.
after this Massage "The result is a tie! Would you like to play new game?(yes or no)", i used "compare(userChoice, computerChoice);" to run again this code. its not working.
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) {
var newChoice = prompt ("The result is a tie! Would you like to play new game?(yes or no)");
if ( newChoice === "yes"){
compare(userChoice, computerChoice);
}
else {
return "Have a nice day!";
}
}
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);
Well yes, that's because you call again
compare(userChoice, computerChoice);
at the forth line inside compare function.
try this:
var choices = ['rock', 'paper', 'scissors'];
var makeRandom = function() {
return parseInt(Math.random()*3);
}
function game() {
var userChoice = prompt("Do you choose rock, paper or scissors?");
var index = choices.indexOf(userChoice);
if(index === -1) {
var bl = confirm('Your choice is outof range, would you like to play Again?');
if(bl) game();
}
var computerChoice = makeRandom();
if(index === computerChoice) {
var bl = confirm('It is a tie, would you like to play Again?');
if(bl) { game(); }
} else if((index === 0 && computerChoice === 1) || (index === 1 && computerChoice === 2) || (index === 2 && computerChoice === 0)) {
alert('you loose');
} else {
alert('you win');
}
}
game();

Categories

Resources