Need help resolving the loop issue - javascript

I recently started learning Javascript, enjoying it a lot. So, after learning some info about loops, i decided to improve a simple Rock, Scissors, Paper game. The improvement is to keep player wins and computer wins values as variables, and than loop the function until playerScore variable reaches value of 10. Im not so good at syntax yet, though trying to get the general logic and where i've made a mistake.
To reach my goal, i've declared two variables - playerScore and computerScore, their initial value is 0. After each player win or computer win i decided to add + 1 to variable.
Than start the game, i've declared a function playGame() and looped it using While. The loop seems infinite and more than that, current results are not logging to console. Any help is much appreciated, will help me to understand the logic much more than any courses i've passed.
Here's the code:
var playerScore = 0;
var computerScore = 0;
function getUserChoice() {
var userInput = prompt('Choose stone, scissors or paper');
userInput = userInput.toLowerCase();
if(userInput === 'stone' || userInput === 'paper' || userInput === 'scissors' || userInput === 'bomb') {
return userInput;
}
else {
alert('Error! Choose stone, scissors or paper!');
}
}
function getComputerChoice() {
var randomNumber = Math.floor(Math.random() *3);
if(randomNumber === 1) {
return 'stone';
}
else if(randomNumber === 2) {
return 'paper';
}
else {
return 'scissors';
}
}
function determineWinner (userChoice, computerChoice) {
if(userChoice === computerChoice) {
return 'That's a tie!';
}
if(userChoice === 'stone') {
if(computerChoice === 'scissors') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
else {
if(computerChoice === 'paper') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!'
}
}
}
if(userChoice === 'paper') {
if(computerChoice === 'scissors') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'stone') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player wonи!';
}
}
}
if(userChoice === 'scissors') {
if(computerChoice === 'stone') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
}
}
if(userChoice === 'bomb') {
if(computerChoice === 'stone' || computerChoice === 'scissors' || computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
return 'Player won!';
}
}
}
while(playerScore < 10) {
function playGame() {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
playGame() = false;
}
};
playGame();

You need to move your while-loop into the function playGame().
function playGame() {
while(playerScore < 10) {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
}
}

Related

My code is not running but i have no errors

The project is about making a rock paper scissors game using functions and loops etc.
the code below is how the project looks
the first function is to get the randomized computer choice
the second function is to get the user or players choice
the third function is to play the game and check if the player won or the computer won
the final function is to create a for loop to run the third function a certain number of times to see who is the winner of the game
Been working on it since and have no idea why it doesn't work
```
function getComputerChoice() {
let values = ["rock", "paper", "scissors"];
return values[Math.floor(Math.random() * values.length)];
}
function getPlayerChoice() {
let getChoice = "rock";
let value = getChoice.trim();
let lowCase = value.toLowerCase();
let capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
while (!["Rock", "Paper", "Scissors"].includes(capitalize)) {
value = getChoice.trim();
lowCase = value.toLowerCase();
capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
}
return capitalize;
}
function playRound(playerSelection, computerSelection) {
let games = "";
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return (games =
"player loses!! " + computerSelection + " beats " + playerSelection);
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
return (games =
"player Wins!! " + playerSelection + " beats " + computerSelection);
} else if (playerSelection == computerSelection) {
return (games =
"it a tie noice " + playerSelection + " v " + computerSelection);
} else {
return (games = "euphoria");
}
}
function game() {
let playerScores = 0;
let computerScores = 0;
let computerSelection = "";
let playerSelection = "";
computerSelection = getComputerChoice();
playerSelection = getPlayerChoice();
for (let i = 0; i < 5; i++) {
if (
playRound(
"player loses!! " + computerSelection + " beats " + playerSelection
)
) {
computerScores += 1;
console.log(
"you lost this round!! boo hoo!! scores are " +
computerScores +
" v " +
playerScores
);
} else if (
playRound(
"player Wins!! " + playerSelection + " beats " + computerSelection
)
) {
playerScores += 1;
console.log(
"you Won this round!! hurray!! scores are " +
computerScores +
" v " +
playerScores
);
}
}
if (playerScores > computerScores) {
console.log("congratulations you won this round");
} else if (playerScores < computerScores) {
console.log("im sorry you lost this round");
} else {
console.log("there is a problem");
}
}
game();
```
It doesn't seem that playRound() is returning anything:
function playRound(playerSelection, computerSelection) {
let games = '';
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
games = "player loses!! " + computerSelection + " beats " + playerSelection;
// ADD RETURN HERE
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
games = "player Wins!! " + playerSelection + " beats " + computerSelection;
// ADD RETURN HERE
} else if (playerSelection == computerSelection) {
games = "it a tie noice " + playerSelection + " v " + computerSelection;
// ADD RETURN HERE
} else {
games = "euphoria";
// ADD RETURN HERE
}
}
Explanation
In your game() function definition you are checking if(playRound()). playRound is not returning anything so this is interpreted as a void function, hence, the if will always evaluate to false.

How to change value of outer variable using a inner function?

In following code, the outer variables playerScore and computerScore are not updated when I use the function calcScore? How do I update it, using a function? From what I understand, it is possible to change the value of the outer variable from an inner scope, but why does it not work here?
<script>
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result, playerScore, computerScore) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
}
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
calcScore(result, playerScore, computerScore);
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
Javascript doesn't pass variables by reference - so any modifications you do to playerScore and computerScore within calcScore() are only local to that function.
What you can do is make playerScore and computerScore global variables. That way any modifications will be in the global scope. Alternatively, you could have calcScore() return the modified values.
Using the global method:
<script>
let playerScore = 0;
let computerScore = 0;
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
}
function game() {
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
calcScore(result);
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
Alternative method:
<script>
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result, playerScore, computerScore) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
return [playerScore, computerScore];
}
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
let scores = calcScore(result, playerScore, computerScore);
playerScore += scores[0];
computerScore += scores[1];
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
your defining both of those variables twice so now im confused. do you want to be abled to reuse those variables in the game function without re defining them? because if thats the case then they should be global variables instead of function parameters(you wont be able to use those defined in the function parameter outside of that function).

Rock Paper Scissors JS Game

I'm a complete beginner with JS and I'm struggling to understand the logic with this one. Nothing is being logged in the console, although I am getting the alert inputs. Can anyone point out where I'm going wrong? Is it perhaps something to do with scope? I feel like this should be really simple but I can't get it working.
function computerPlay() {
const options = ['rock', 'paper', 'scissors'];
let result = options[Math.floor(Math.random() * options.length)];
return result;
}
function playRound(playerSelection, computerSelection) {
let selection = prompt('Please enter your selection');
let playerScore = 0;
let computerScore = 0;
let result = "";
computerSelection = computerPlay();
playerSelection = selection.toLowerCase();
if (playerSelection == 'rock') {
if (computerSelection == 'rock') {
return ["It's a draw!", playerScore + 1, computerScore + 1];
} else if (computerSelection == 'paper') {
return ["You lose!", computerScore + 1];
} else {
return ["You win!", computerScore + 1];
}
} else if (playerSelection == 'paper') {
if (computerSelection == 'paper') {
return "It's a draw!";
} else if (computerSelection == 'scissors') {
return "Computer wins!";
} else {
return "You win!";
}
} else if (playerSelection == 'scissors') {
if (computerSelection == 'scissors') {
return "It's a draw!"
} else if (computerSelection == 'rock') {
return "Computer wins!"
} else {
return "You win!"
}
}
return result + "Player Score = " + playerScore + "Computer Score = " + computerScore;
}
function game() {
for (let i = 0; i < 5; i++) {
computerPlay();
playRound();
}
}
console.log(game())
Move your console log from where it is to inside the game() function like so:
for (let i = 0; i < 5; i++) {
console.log(playRound());
}
You also don't need to call computerPlay() in the game function, as it is doing nothing.
Modify the game function this way.
function game() {
for (let i = 0; i < 5; i++) {
const result = playRound();
console.log(result)
}
}
game()
Then you call game(). You will be able to see your console log and also you do not need to call the computerPlay function inside the game function. It's functionality is already called in the playRound function. Hope this helps cheers

why is my function if/else if/ else if statement returning the same answer?

I have a rock, paper, scissors game set up with the user clicking on the buttons labeled "Rock", "Paper", "Scissors" which results in the userChoice.
When I run the program the compareChoices() function always returns "The result is a tie, let's play again!", I don't understand why.
< article >
< button onclick = "rockPaperScissors('Rock')" > Rock < /button>
<button onclick="rockPaperScissors('Paper')">Paper</button >
< button onclick = "rockPaperScissors('Scissors')" > Scissors < /button>
</article >
< script type = "text/javascript" >
function rockPaperScissors(userchoice) {
alert("You chose " + userchoice + " ...the computer chose " + getComputerChoice() + ".");
compareChoices();
}
function getComputerChoice() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Rock";
} else if (computerChoice < 0.67) {
computerChoice = "Paper";
} else {
computerChoice = "Scissors";
}
return computerChoice;
}
function compareChoices(userChoice, ComputerChoice) {
if (userChoice === ComputerChoice) {
alert("The result is a tie, let's play again!");
} else if (userChoice === "Rock") {
if (ComputerChoice === "Scissors") {
alert("Congratulations, you win!");
} else {
alert("The computer wins! Care to play again?");
}
} else if (userChoice === "Scissors") {
if (ComputerChoice === "Rock") {
alert("The computer wins, let's play again!");
} else {
alert("Yippie! You win!");
}
} else if (userChoice === "Paper") {
if (ComputerChoice === "Rock") {
alert("The computer wins. Don't give up, try again!");
} else {
alert("Hail the all mighty visitor. Give it another go!");
}
}
} < /script>
You aren't passing anything into compareChoices
< article >
< button onclick = "rockPaperScissors('Rock')" > Rock < /button>
<button onclick="rockPaperScissors('Paper')">Paper</button >
< button onclick = "rockPaperScissors('Scissors')" > Scissors < /button>
</article >
< script type = "text/javascript" >
function rockPaperScissors(userchoice) {
var computerChoice = getComputerChoice();
alert("You chose " + userchoice + " ...the computer chose " + computerChoice + ".");
compareChoices(userChoice, computerChoice);
}
function getComputerChoice() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Rock";
} else if (computerChoice < 0.67) {
computerChoice = "Paper";
} else {
computerChoice = "Scissors";
}
return computerChoice;
}
function compareChoices(userChoice, ComputerChoice) {
if (userChoice === ComputerChoice) {
alert("The result is a tie, let's play again!");
} else if (userChoice === "Rock") {
if (ComputerChoice === "Scissors") {
alert("Congratulations, you win!");
} else {
alert("The computer wins! Care to play again?");
}
} else if (userChoice === "Scissors") {
if (ComputerChoice === "Rock") {
alert("The computer wins, let's play again!");
} else {
alert("Yippie! You win!");
}
} else if (userChoice === "Paper") {
if (ComputerChoice === "Rock") {
alert("The computer wins. Don't give up, try again!");
} else {
alert("Hail the all mighty visitor. Give it another go!");
}
}
} < /script>
you have to put the computerchoice into variable, and call comparechoices function with same computerchoice.
function rockPaperScissors(userchoice) {
var computerchoice = getComputerChoice();
alert("You chose " + userchoice + " ...the computer chose " + computerchoice + ".");
compareChoices(userchoice, computerchoice);
}
You need to pass the arguments to compareChoices().
function rockPaperScissors(userchoice) {
alert("You chose " + userchoice + " ...the computer chose " + getComputerChoice() + ".");
compareChoices(userchoice, getComputerChoice());
}
You should only alert one time since they are going to come so close together. Something like this:
function compareChoices(userChoice, ComputerChoice) {
var message;
if (userChoice === ComputerChoice) {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - The result is a tie, let's play again!";
} else if (userChoice === "Rock") {
if (ComputerChoice === "Scissors") {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - Congratulations, you win!";
} else {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - The computer wins! Care to play again?");
}
} else if (userChoice === "Scissors") {
if (ComputerChoice === "Rock") {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - The computer wins, let's play again!";
} else {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - Yippie! You win!";
}
} else if (userChoice === "Paper") {
if (ComputerChoice === "Rock") {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - The computer wins. Don't give up, try again!";
} else {
message = "Computer: " + ComputerChoice + ", User: " + userChoice + " - Hail the all mighty visitor. Give it another go!";
}
}
alert(message);
}

Having a hard time calculating totals Javascript

I cant seem to figure out why I cant calculate the points and keep them for each user totals.. Any suggestions? Please help. I was able to build this game using prompts etc.. but trying to bring it to life in a browser has been a challenge..
Here is the code:
function getName() {
var name = document.getElementById('fName').value;
// console.log(name);
$(".greetingPlayer").append("<h3 class='greeting'>Greetings " + name + "!</h3><br><h4>Please choose from the following Weapons...</h4>");
$(".statsA").css("display", "none");
}
var userChoice;
function choices(weapon) {
userChoice = weapon;
// console.log(userChoice);
$(".greetingPlayer").append("<h4 class='userChoice'>Users Choice : " + userChoice + "!</h4>");
var computerChoice = Math.random();
if (computerChoice <= 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
// console.log(computerChoice);
$(".greetingPlayer").append("<h4 class='computerChoice'>Computers Choice : " + computerChoice + "!</h4>");
function compare(choice1, choice2) {
var playing = true;
var human = 0;
var comp = 0;
while (playing) {
if (choice1 === choice2) {
console.log("The result is a tie!");
human = score;
comp = score;
} 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!");
}
} else {
console.log("That's not an option! Do it over " + name + " and try again!");
}
playing = false;
}
console.log("human : " + human);
console.log("comp : " + comp);
var numpoints = 0;
function points() {
if (++score >= str.length) {
numpoints++;
document.getElementByClassName("points").textContent = "Score: " + numpoints;
}
}
}
compare(userChoice, computerChoice);
}
// $(".greetingPlayer").append("<h4 class='userWeapon'> " + name + "! You win!</h4>");
I figured it out, my scope was all wrong and I have no idea why I was attempting to add a loop on the bottom. However this seemed to solve...
function getName(){
var name = document.getElementById('fName').value;
// console.log(name);
$(".greetingPlayer").append("<h3 class='greeting'>Greetings " + name + "!</h3><br><h4>Please choose from the following Weapons...</h4>");
$(".statsA").css("display", "none");
}
// Here we declare a variable to represent a User's Choice outside of the function scope
var userChoice;
var computerChoice;
//These variables are created to keep score and are declared w/ zero for addition.
var compScore = 0;
var userScore = 0;
// Here we declare a function to compare a userChoice vs compChoice
var choices = function(weapon){
userChoice = weapon;
// console.log(userChoice);
computerChoice = Math.random();
// console.log(computerChoice);
if (computerChoice <= 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
$(".toolChoice").html(" " + userChoice + "!");
// console.log(computerChoice);
$(".toolChoiceB").html(" " + computerChoice + "!");
function compare(choice1, choice2){
if(choice1 === choice2){
console.log("The result is a tie!");
}else if(choice1 === "rock"){
if(choice2 === "scissors"){
console.log("rock wins!");
userScore++;
}else{
console.log("paper wins!");
compScore++;
}
}else if(choice1 === "paper"){
if(choice2 === "rock"){
console.log("paper wins!");
userScore++;
}else{
console.log("scissors wins!");
compScore++;
}
}else if(choice1 === "scissors"){
if(choice2 === "paper"){
console.log("scissors wins!");
userScore++;
}else{
console.log("rock wins!");
compScore++;
}
}else{
console.log("That's not an option! Do it over "
+ name + " and try again!");
}
}
// end of compare function
// compare function called
compare(userChoice, computerChoice);
// This consoles the score, use this as a start point for displaying the score.
// console.log("human : " + userScore);
// console.log("comp : " + compScore);
// This jQuery displays the score for each party
// This is the score for Humans
$('.scoreA').html(" " + userScore);
// This is the score for Computers
$('.scoreB').html(" " + compScore);
}

Categories

Resources