I am making a game for RockPaperScissors. I have a function that generates the computers choice, then have a function that reacts to the clicking of a button, then a function for playing the game combining both functions.
I have tried accessing it through the functions, and have been doing research but cant find a way to get the variable to make its way to the last function. Do I have to combine all of them to a single function in order to get the variable.
/*This function generates the computer's choice and then presents a rock image, removing it after 2 seconds.*/
function computerChoice() {
let compChoice = Math.random();
if (compChoice < 0.33) {
compChoice = "rock";
cpuChoice.classList.add(rockImage, rockImage2);
setTimeout(function () {
cpuChoice.classList.remove(rockImage, rockImage2);
}, 2000);
} else if (compChoice < 0.66 && compChoice > 0.33) {
compChoice = "paper";
cpuChoice.classList.add(paperImage, paperImage2);
setTimeout(function () {
cpuChoice.classList.remove(paperImage, paperImage2);
}, 2000);
} else {
compChoice = "scissors";
cpuChoice.classList.add(scissorImage, scissorImage2);
setTimeout(function () {
cpuChoice.classList.remove(scissorImage, scissorImage2);
}, 2000);
}
}
/*Here is the function thats having issues, I cant seem to get the gameResults innerHTML to change since it wont gather the compChoice.*/
function playGame(humanChoice, compChoice) {
if (humanChoice === compChoice) {
gameResults.innerHTML = "tie";
} else if (humanChoice === "rock" && compChoice === "scissor") {
gameResults.innerHTML = "You won!";
} else if (humanChoice === "rock" && compChoice === "paper") {
gameResults.innerHTML = "The computer won!";
} else if (humanChoice === "paper" && compChoice === "rock") {
gameResults.innerHTML = "You won!";
} else if (humanChoice === "paper" && compChoice === "scissor") {
gameResults.innerHTML = "The computer won!";
} else if (humanChoice === "scissor" && compChoice === "rock") {
gameResults.innerHTML = "The computer won!";
} else if (humanChoice === "scissor" && compChoice === "paper") {
gameResults.innerHTML = "You won!";
} else {
gameResults.innerHTML = "Not Possible";
}
}
/*This function generates the human's choice from a click and then presents an image of the choice, removing it after 2 seconds. Then calls for computerChoice(), and attempts to call the playGame functions.*/
allButtons.forEach(function (e) {
e.addEventListener("click", function () {
const choice = e.dataset.play;
if (choice === "rock") {
humanChoice = "rock";
computerChoice();
yourChoice.classList.add(rockImage, rockImage2);
setTimeout(function () {
yourChoice.classList.remove(rockImage, rockImage2);
}, 2000);
playGame(humanChoice, compChoice);
} else if (choice === "paper") {
humanChoice = "paper";
computerChoice();
yourChoice.classList.add(paperImage, paperImage2);
setTimeout(function () {
yourChoice.classList.remove(paperImage, paperImage2);
}, 2000);
playGame(humanChoice, compChoice);
} else if (choice === "scissors") {
humanChoice = "scissors";
computerChoice();
yourChoice.classList.add(scissorImage, scissorImage2);
setTimeout(function () {
yourChoice.classList.remove(scissorImage, scissorImage2);
}, 2000);
playGame(humanChoice, compChoice);
}
});
});
I am expecting the gameResults.innerHTML to change, but it wont because it wont gather the CompChoice's variable to compare to the HumanChoices.
Related
I read all the previous and similar topics and I didnt get my answer
The problem is that the function "rockPaperScissors" doesn't return anything in the close despite the fact that I have put return messages inside for different conditions,
Thanks in advance ,
what is the problem and solution and what have I done wrong?
let playerScore = 0;
let computerScore = 0;
let pcChoice = Math.floor(Math.random() * 3) + 1;
if (pcChoice === 1) {
pcChoice = "rock";
} else if (pcChoice === 2) {
pcChoice = "paper";
} else {
pcChoice = "scissors";
}
let userInput = prompt("Rock ?\nPaper?\nScissors?")
userInput = userInput.toLowerCase();
let errorMessage = "You have put a wrong input"
if (! ((userInput === "rock") || (userInput === "paper") || (userInput === "scissors"))) {
alert(errorMessage);
} else {
rockPaperScissors(userInput, pcChoice);
console.log("Userscore is " + playerScore + "and Computerscore is " + computerScore);
};
if (playerScore > computerScore) {
console.log("You are the winner");
} else if (computerScore > playerScore) {
console.log("Computer is the winner");
} else {
console.log("It's a draw");
}
function rockPaperScissors(user, pc) {
let winningMessage = "You Won!";
let drawMessage = "it's a draw!";
let losingMessage = " You lost!";
if (user === "rock" & pc === "scissors") {
playerScore++;
return `You won! ${user} beats ${pc}`;
} else if (user === "paper" & pc === "rock") {
playerScore++;
return `You won! ${user} beats ${pc}`;
} else if (user === "scissors" & pc === "paper") {
playerScore++;
return `You won! ${user} beats ${pc}`;
} else if (user === pc) {
return drawMessage;
} else {
computerScore++;
return `You won! ${pc} beats ${user}`;
}
}
I'm new to coding and javascript. I'm working on an assignment where I have to create a Rock Paper Scissors game that has 2 modes, single player and best out of three. In the best out of three mode, you need to create a system to remember the score of the user and the bot. And it needs a loop to run as many rounds as possible until there is a player that wins at least two rounds. Once the game ends, you can ask the human player if he/she wants to play again using a confirm() function. I have the base game but I cant figure out how to have the game loop until one player wins 2 rounds. I also cant figure out how to add a play again option. If someone can please help I would greatly appreciate it.
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();
let playerScore = 0;
let computerScore = 0;
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()
}
You can pass a parameter to the round() function to tell it how many wins are needed. Then, put the main code in a loop:
const round = (winsNeeded) => {
let playerScore = 0;
let computerScore = 0;
while (playerScore < winsNeeded && computerScore < winsNeeded) {
const res = play();
console.log(res)
if (res[0] == 'P') playerScore++;
else if (res[0] == 'C') computerScore++;
console.log(`Score: you ${playerScore}, computer ${computerScore}`);
}
if (playerScore == winsNeeded) {
console.log("Player won that round.");
}
else {
console.log("Computer won that round.");
}
}
while (true) {
let cnt = 1;
const mode = prompt("Please press 1 for single game mode or 2 for best out of 3 mode");
if (mode === '2') cnt = 2;
round(cnt);
const choice = prompt("Play again?");
if (choice[0].toLowerCase() != 'y') break;
}
For every 2 round you can check for the current status of the game. Also made some changes on the play logic
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!";
}
//little change in logic here----
if (computerChoice === "rock") {
if (userChoice === "scissors") {
return "Computer wins";
} else {
if (userChoice === "paper")
return "Player wins";
}
}
if (computerChoice === "paper") {
if (userChoice === "rock") {
return "Computer wins";
} else {
if (userChoice === "scissors")
return "Player wins";
}
}
if (computerChoice === "scissors") {
if (userChoice === "paper") {
return "Computer wins";
} else {
if (userChoice === "rock")
return "Player wins";
}
}
};
const round = () => {
const res = play();
let playerScore = 0;
let computerScore = 0;
console.log(res)
cnt--
wins[cnt] = res.startsWith("Player") ? 1 :res.includes("tie") ?-1:0;
console.log(wins)
if (cnt === 0) {
const total = wins.filter((a) => a==1)
console.log(`You beat the computer ${total.length} time${total.length===1?"":"s"}`)
playAgain()
}else if(cnt == 1){ // Check for every round
var el2 = wins[2];
var el1 = wins[1];
if(el2 == el1 && el1!=-1){
const total = wins.filter((a) => a==1)
console.log(`You beat the computer ${total.length} time${total.length===1?"":"s"}`)
playAgain()
}
}
if(pa){
setTimeout(round, 10) // else go again
}else{
prompt("Thank you for playing")
}
}
let pa = true;
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()
function playAgain(){
if(confirm('Do you want to play again ?')){
pa = true
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()
}else{
pa=false
}
}
i'm learning javascript and currently making a rock, paper, scissor game using only javascript. the game will have 1 round mode and 3 rounds mode but as i finished to code the 1 round mode i found out having problem display result, whoever win the game it display "the game is tie" and can't find where s the mistake, can anybody help me?
// Player choice
var getPlayerChoice = function() {
var playerChoice = prompt("Choose rock, paper, or scissors");
while (playerChoice !== 'rock' && playerChoice !== 'paper' && playerChoice !== 'scissors') {
if (playerChoice === null) {
break;
}
playerChoice = prompt("Invalid ! you have to choose rock, paper, or scissors");
}
return playerChoice;
}
// Computer Choice
var getComputerChoice = function () {
var randomNum = Math.random();
if ( randomNum < 0.3333 ) {
return "rock";
} else if ( randomNum > 0.3333 && randomNum < 0.6666 ) {
return "scissors";
} else {
return "paper";
}
}
// Winner Function
var getWinner = function (playerChoice, computerChoice) {
if (computerChoice === playerChoice) {
return "The Game is Tie";
} else if (computerChoice === "paper") {
if (playerChoice === "scissors") {
return "player win";
} else if (playerChoice === "rock") {
return "computer win";
}
} else if (computerChoice === "rock") {
if (playerChoice === "scissors") {
return "computer win";
} else if (playerChoice === "paper") {
return "player win";
}
} else if (computerChoice === "scissors") {
if (playerChoice === "rock") {
return "player win";
} else if (playerChoice === "paper") {
return "computer win";
}
}
}
// Single game mode
var singleRound = function() {
var playerChoice = getPlayerChoice();
if (playerChoice === null) {
return;
}
var computerChoice = getComputerChoice();
var winner = getWinner(playerChoice, computerChoice);
var message = " You chose: " + playerChoice + "\n Computer chose: " + computerChoice;
if (winner === "player") {
alert(message + "\nYou won!");
} else if (winner === "computer") {
alert(message + "\nYou lost!");
} else {
alert(message + "\nThe Game is Tie");
}
return winner;
}
var mode = prompt("Welcome!\n \nplease insert 1 for single round mode\n2 for 3 rounds mode");
if (mode === '1') {
singleRound();
} else if (mode === '2') {
threeRoundsMode();
}
Your getWinner() function returns player win or computer win, but your code that calls it is looking for return values of player or computer.
Because the code never gets what it's looking for it defaults to `'The Game is Tie'
This is happening because of a mistake in the singleRound() function. if (winner === "player") { should be if (winner === "player win") { and similarly the if (winner === "computer") { should say if (winner === "computer win") { so that the text being compared matches. Right now, it is comparing "player" and "player win", then "computer" and "computer win" so then the else clause is reached regardless of actual game outcome.
I'm trying to make a rpsls game using javascript and jquery. I have most of it functioning, but I can't seem to get the variables to reset to 0 at the end of 5 throws. I used an if statement to reset the round variable to 0, but I can't seem to figure out how to reset the two scores to 0 after 5 rounds.
$(document).ready(function() {
var round = 0
var yourScore = 0
var compScore = 0
$(".shoot").on("click", function() {
var choiceRPS = ['rock', 'paper', 'scissor','lizard','spock'];
var ranNum = Math.floor(Math.random() * choiceRPS.length);
var compChoice = choiceRPS[ranNum];
var userChoice = this.id;
round++;
$("#round").html(round);
var compChoice = choiceRPS[ranNum];
console.log(userChoice);
console.log(compChoice);
if (compChoice == userChoice) {
};
if (userChoice === "rock") {
if (compChoice === "lizard" || compChoice === "scissor") {
yourScore++;
$("#yourScore").html(yourScore);
} else {
if (compChoice === "paper" || compChoice === "spock") {
compScore++;
$("#computerScore").html(compScore);
}
}
};
if (userChoice === "paper") {
if (compChoice === "rock" || compChoice === "spock") {
yourScore++;
$("#yourScore").html(yourScore);
} else {
if (compChoice === "scissor" || compChoice === "lizard") {
compScore++;
$("#computerScore").html(compScore);
}
}
};
if (userChoice === "scissor") {
if (compChoice === "paper" || compChoice === "lizard") {
yourScore++;
$("#yourScore").html(yourScore);
} else {
if (compChoice === "rock" || compChoice === "spock") {
compScore++;
$("#computerScore").html(compScore);
}
}
};
if (userChoice === "lizard") {
if (compChoice === "spock" || compChoice === "paper") {
yourScore++;
$("#yourScore").html(yourScore);
} else {
if (compChoice === "rock" || compChoice === "scissor") {
compScore++;
$("#computerScore").html(compScore);
}
}
};
if (userChoice === "spock") {
if (compChoice === "rock" || compChoice === "scissor") {
yourScore++;
$("#yourScore").html(yourScore);
} else {
if (compChoice === "lizard" || compChoice === "paper") {
compScore++;
$("#computerScore").html(compScore);
}
}
};
if (round === 5) {
round -=5;
yourScore -= yourScore;
compScore -= compScore;
if (yourScore>compScore) {
$('#win').modal({
keyboard: false
});
} else if (yourScore<compScore) {
$('#lose').modal({
keyboard: false
});
} else if (yourScore==compScore) {
$('#tie').modal({
keyboard: false
});
};
};
});
});
I made a plnkr and realized that your issue is that you're only updating the #yourScore and #computerScore elements when the respective element wins. You should move the element updates to outside your if statements. This also simplifies your code a bit too.
if (userChoice === "rock") {
if (compChoice === "lizard" || compChoice === "scissor") {
yourScore++;
} else {
if (compChoice === "paper" || compChoice === "spock") {
compScore++;
}
}
};
if (userChoice === "paper") {
if (compChoice === "rock" || compChoice === "spock") {
yourScore++;
} else {
if (compChoice === "scissor" || compChoice === "lizard") {
compScore++;
}
}
};
if (userChoice === "scissor") {
if (compChoice === "paper" || compChoice === "lizard") {
yourScore++;
} else {
if (compChoice === "rock" || compChoice === "spock") {
compScore++;
}
}
};
if (userChoice === "lizard") {
if (compChoice === "spock" || compChoice === "paper") {
yourScore++;
} else {
if (compChoice === "rock" || compChoice === "scissor") {
compScore++;
}
}
};
if (userChoice === "spock") {
if (compChoice === "rock" || compChoice === "scissor") {
yourScore++;
} else {
if (compChoice === "lizard" || compChoice === "paper") {
compScore++;
}
}
};
$("#yourScore").html(yourScore);
$("#computerScore").html(compScore);
http://plnkr.co/edit/FofGShFtTMED8IY4fP1b?p=preview
Also, in your win checking, you should reset the variables after you check who won, or else it will always be a tie since yourScore and compScore will both be 0.
Also, this looks like some good exercise so I'm going to optimize your solution a bit :)
Have you tried moving your declarations outside of your document.ready? You can still initialise them inside it.
i.e.
var round = 0;
var yourScore = 0;
var compScore = 0;
$(document).ready(function() {
...
I've just tried your solution and it seems to be working. It resets to 0, then on next button click it increments to 1 again.
I need a bit of help with a basic JavaScript version of Rock-Paper-Scissors I'm working on. I just started learning today and would like to keep the code as intact as possible, if possible.
The main problem I'm having is with the loop. It continues despite me setting 'again' to 'no' (through the prompt). Also, the computer always seems to choose Rock... I have a feeling that I'm just missing something simple:
<html>
<script type="text/javascript">
var myChoice = "";
var compChoice = "";
var again;
while (again = "yes")
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice = "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice = "scissors";
}
if (compChoice = myChoice)
{
alert("It's a tie!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (compChoice = "rock")
{
if(myChoice = "scissors")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "paper")
{
if (myChoice = "rock")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "scissors")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "scissors")
{
if (myChoice = "rock")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
}
};
</script>
</html>
You are using = instead of == in the while statement and same in all the if statements also
= is the assignment operator, while == is the comparison operator
var myChoice = "";
var compChoice = "";
var again;
do
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice == "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice == "scissors";
}
if (compChoice == myChoice)
{
alert("It's a tie!");
}
else if (compChoice == "rock")
{
if(myChoice == "scissors")
{
alert("You lose!");
}
else if (myChoice == "paper")
{
alert("You win!");
}
}
else if (compChoice == "paper")
{
if (myChoice == "rock")
{
alert("You lose!");
}
else if (myChoice == "scissors")
{
alert("You win!");
}
}
else if (compChoice == "scissors")
{
if (myChoice == "rock")
{
alert("You win!");
}
else if (myChoice == "paper")
{
alert("You lose!");
}
}
again = prompt("Would you like to play again?(yes/no)");
}while (again == "yes");
Demo: Fiddle
One major issue is that you are assigning values instead of comparing values in multiple places.
a = 2 // assigns a to value 2, and evaluates to true
a == 2 // compares a to 2, only evaluates to true if a has value 2