Javascript Rock Paper Scissors not working - javascript

I tried making rock paper scissors in JS. I wanted it to be so that it would count points and announce the winner. But my code is a mess. The computer always wins, always prints that you lose. I cant really make out what the issues are. I also tried to make it so that after every round, you can make a new choice, but that didnt really work out as planned either.
var pcChoice = ["Steen", "Papier", "Schaar"];
var userChoice = prompt("Steen, papier of schaar?");
var pcWins = 0;
var userWins = 0;
var totalWins = pcWins + userWins
var win = ("Je hebt de ronde gewonnen!")
var Verlies = ("Je hebt verloren")
function randomNumber() {
return (Math.floor(Math.random() * 3));
}
console.log("Computer koos: " + pcChoice[randomNumber()]);
console.log("Jij koos: " + userChoice);
if (pcWins + userWins === 2) {
prompt("Nieuwe keuze")
}
if (pcWins + userWins === 1) {
prompt("Nieuwe keuze")
}
while (pcWins + userWins < 3) {
if (userChoice === pcChoice) {
console.log("Gelijkspel");
} else if (userChoice === "Steen" && pcChoice === "Schaar") {
console.log(win) + userWins++
} else if (userChoice === "Papier" && pcChoice === "Steen") {
console.log(win) + userWins++
} else if (userChoice === "Schaar" && pcChoice === "Papier") {
console.log(win) + userWins++
} else {
console.log(Verlies) + pcWins++
}
}
// Het volgende zal de winner uitprinten
if (pcWins > userWins) {
console.log("De computer wint!")
} else {
console.log("Je hebt gewonnen")
}

A lot of typos and beginner mistakes.
I have cleaned your code in the snippet below.
Always make sure your While loops don't loop indefinitely!
var pcChoices = [
'Steen',
'Papier',
'Schaar'
];
var userChoice = prompt('Steen, papier of schaar?');
var pcWins = 0;
var userWins = 0;
var totalWins = pcWins + userWins;
var win = ('Je hebt de ronde gewonnen!');
var Verlies = ('Je hebt verloren');
function randomNumber() {
return (Math.floor(Math.random() * 2));
}
console.log('Computer koos: ' + pcChoices[randomNumber()]);
console.log('Jij koos: ' + userChoice);
if (pcWins + userWins === 2) {
prompt('Nieuwe keuze');
}
if (pcWins + userWins === 1) {
prompt('Nieuwe keuze');
}
while (pcWins + userWins < 3) {
var pcChoice = pcChoices[randomNumber()];
if (userChoice === pcChoice) {
console.log('Gelijkspel');
break;
}
else if (userChoice === 'Steen' && pcChoice === 'Schaar') {
console.log(win);
userWins++;
}
else if (userChoice === 'Papier' && pcChoice === 'Steen') {
console.log(win);
userWins++;
}
else if (userChoice === 'Schaar' && pcChoice === 'Papier') {
console.log(win);
userWins++;
}
else {
console.log(Verlies);
pcWins++;
}
} // Het volgende zal de winner uitprinten
if (pcWins > userWins) {
console.log('De computer wint!');
}
else {
console.log('Je hebt gewonnen');
}

I hope this helps.
It takes things one round at a time rather than all at once. The result or a round is calculated by looking up a little table. There is no reason that your version of calculating a win would not work though.
Please forgive my Dutch.
var choice = {STEEN: 0, PAPIER: 1, SCHAAR: 2};
var resultMatrix = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]];
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function playRound(round){
var userInput = prompt("Round " + round + ": steen, papier of schaar?");
var userChoice = choice[userInput.toUpperCase()];
var pcInput = Object.keys(choice)[getRandomInt(0,2)];
var pcChoice = choice[pcInput];
var result = resultMatrix[userChoice][pcChoice];
console.log("Ronde " + round);
console.log("Jij koos: " + userInput.toUpperCase());
console.log("Computer koos: " + pcInput);
switch(result){
case -1:
console.log("De computer wint!");
break;
case 0:
console.log("Gelijkspel");
break;
case 1:
console.log("Je hebt gewonnen");
break;
}
console.log(" ");
return result
};
var totalUserWins = 0;
for(var i=1; i<=3; i++){ totalUserWins += playRound(i); }
console.log("Laatste");
if (totalUserWins > 0) { console.log("Je hebt gewonnen"); } else
if (totalUserWins === 0) { console.log("Het is een gelijkspel"); } else
if (totalUserWins < 0) { console.log("De computer wint!"); }

Related

Converting from score to grade

I am struggling all day with this one. I need to call function scoreGrade in order to get grade as a number. Could you tell me what do I need to correct? I tried with this code, but I can't figure out the rest. :/
function endQuiz() {
var grade = scoreGrade();
if (myAnswers[(lengthofobject-1)] {
var output = "<div class='output'>Резултат<br>";
var questionResult = "NA";
//console.log('Quiz Over');
for (var i = 0; i < myAnswers.length; i++ || "ten-countdown"<1)) {
if (data.quizcontent[i].correct == myAnswers[i]) {
questionResult = '<span class="glyphicon glyphicon-ok-circle" aria-hidden="true"></span>';
correct++;
} else {
questionResult = '<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>';
}
output = output + '<p>Питање ' + (i + 1) + ' ' + questionResult + '</p> ';
}
var grade = scoreGrade(correct, lengthofobject)
document.getElementById("ocena").innerHTML = grade;
function scoreGrade(){
let score = (correct / lengthofobject) * 100;
let grade;
if (score>=85) {grade ='5'}
else if (score>=70) {grade ='4'}
else if (score>=55) {grade ='3'}
else if (score>=40) {grade ='2'}
else {grade ='1'}
return grade;
}
clearInterval(endTime);
output = output + '<p>Имате ' + correct + ' од ' + lengthofobject + ' тачних одговора.</p></div> ';
document.getElementById("quizContent").innerHTML = output;
} else {
//console.log('not answered');
}
I'm guessing your issue is inside the scoreGrade function, which does not return anything. Let's modify it like so:
function scoreGrade(correct, questions.length) {
let score = (correct/questions.length) * 100;
if (score>=85) { return (<h4>Vaša ocena je 5.</h4>); }
else if (score>=70) { return (<h4>Vaša ocena je 4.</h4>); }
else if (score>=55) { return (<h4>Vaša ocena je 3.</h4>); }
else if (score>=40) { return (<h4>Vaša ocena je 2.</h4>); }
else { return (<h4>Vaša ocena je 1.</h4>); }
}
This function would work, but not with vanilla js. Returning html in js is a jsx practice. If you're not using jsx consider just returning the grade value as a string or integer.

Rock paper scissors Javascript

I'm trying to build an RPS game with Javascript, using a click event as input.
I can get the program to see Watson's input and clock the number of games I've lost, but I can't get the program to recognize my input.
What steps have I missed out? Please check out the following link for all the code including HTML.
https://codepen.io/szewah/pen/daMKbK
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
//gueses
var computerGuess = rockPaperScissors[Math.floor(Math.random()*rockPaperScissors.length)];
var myGuess = function (input) {
if (input === 'Rock' || input === 'Paper' || input === "Scissors") {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins =0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('userchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame () {
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
// array for choices of rock, paper, scissors
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
function myGuessFn(input) {
if (input === 'Rock' || input === 'Paper' || input === 'Scissors') {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins = 0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('computerchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame(event) {
var myGuess = myGuessFn(event.target.innerHTML);
var computerGuess = rockPaperScissors[Math.floor(Math.random() * rockPaperScissors.length)];
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
#rock-btn,
#paper-btn,
#scissors-btn {
cursor: pointer;
}
<div class="container">
<h1>Press Rock Paper Scissors to play</h1>
<div class="choices">
<div id="rock-btn">Rock</div>
<div id="paper-btn">Paper</div>
<div id="scissors-btn">Scissors</div>
</div>
<hr>
<div class="resultChoice">
<p id="userchoice-text"></p>
<br>
<p id="computerchoice-text"></p>
</div>
<hr>
<div class="results">
<p id="wins-text"></p>
<p id="losses-text"></p>
<p id="ties-text"></p>
</div>
</div>

showing variable value in <p> paragraph using getElementById.innerHTML in Javascript

I'm trying to write a Blackjack code using Javascript, and showing the result in an HTML page. I have written the logic already, but I can't get to show the results in paragraph by ID, using getElementById.innerHTML. I don't know how to make it right. Could you please help me with this? I'm running out of time :(. here's the code:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
</body>
</html>
As #nnnnnn has mentioned that your html tags are not even loaded when your JS has executed and hence the issue. Try something like below to correct the issue:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
<script>
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</body>
</html>
your script is loading before the document that has the elements in it. Enclose your script in:
window.onload=function() {
//all of your JavaScript code
}

Infinite Loop in JavaScript - While Loop

Does anyone know why this may be causing an infinite loop. I just can't see why!
I feel the issue may be with my while loop under play to five.
The while loop should be stopping at 5 and when the player or computer reaches this the game should stop.
This is Rock, Paper, Scissors. The result of each game is either player win, computer win or draw.
The game should end once either player reaches 5 wins.
The problem is the game is not ending as intended!
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.");
return prompt("Please choose either 'rock', 'paper', or 'scissors'");
}
function getPlayerMove() {
return getInput();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
}
else if (randomNumber < 0.66) {
return "paper";
}
else {
return "scissors";
}
}
function getComputerMove() {
return randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
// A big limitation of this game is the user is only allowed to choose once! To allow more choices you'd need to design the program differently
function playToFive() {
var playerWins = 0;
var computerWins = 0;
var playerMove = getPlayerMove();
while ((playerWins <= 5) || (computerWins <= 5)) {
var computerMove = getComputerMove();
var winner = getWinner(getPlayerMove, getComputerMove);
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "player") {
playerWins += 1;
}
else if (winner === "computer") {
computerWins += 1;
}
if ((playerWins = 5) || (computerWins = 5)) {
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
playToFive ();
Problem is this line
var winner = getWinner(getPlayerMove, getComputerMove);
you are passing the function reference to the getWinner() method
var winner = getWinner(playerMove , computerMove );
Which means that you need to get moves again later, so change your method to (multiple issues fixed in your code)
function playToFive()
{
var playerWins = 0;
var computerWins = 0;
while ((playerWins <= 5) && (computerWins <= 5)) //this line has && instead of ||
{
var computerMove = getComputerMove();
var playerMove = getPlayerMove(); //this line is now inside while loop
var winner = getWinner( playerMove , computerMove );
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "Player") { //P caps
playerWins += 1;
}
else if (winner === "Computer") { //C caps
computerWins += 1;
}
if ((playerWins == 5) || (computerWins == 5)) { //= is replaced by ==
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
In order for this if to run accordingly:
if ((playerWins = 5) || (computerWins = 5)) {}
You'll need to use the == operator, because just one = is used for value assignation.
if ((playerWins == 5) || (computerWins == 5)) {}
Firstly in the while loop you need to change it too a && statement otherwise if the computer is 8 and the player is 3 the loop will continue until both players are >5.
I Think first you should understand the difference between (==) and (===) here.
Use This Code (Conditional Code not assignment)
if ((playerWins == 5) || (computerWins == 5)) { //use logical Operator not assignment Oprtr.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Instead of ##
if ((playerWins = 5) || (computerWins = 5)) { // Error Code.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Problem is this line
you are passing the function reference to the getWinner() method
use this
var winner = getWinner(playerMove , computerMove );
instead of
var winner = getWinner(getPlayerMove, getComputerMove);
For This Function...
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
Every time this method set tie as winner.
But you should know the difference between (==) equalto and (===) equal value and equal type here
Thanks guys. There were quite a few issues.
Cheers guys. Definitely needed && rather than ||. The || was resulting in the game continuing even
Also var winner = getWinner(getPlayerMove, getComputerMove) was required. This was causing an infinite loop.

How do I end javascript program mid program

I need some help ending my program. Is there a command to end it halfway through? In this short guess the number game i made everything goes fine unless the first person wins because it has to complete the loop even after the game has ended
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
Use break; to break the while loop like this:
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
break; // it will break the while loop
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
break; // it will break the while loop
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
Or you can define the process as a function when someone win the game return a value and it will end :
function game() {
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
return ; // it will end the function
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
return ; // it will end the function
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
}
game();
I think you are looking for continue
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
continue;
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
The break statement, which was briefly introduced with the switch
statement, is used to exit a loop early, breaking out of the enclosing
curly braces.
To handle all such situations, JavaScript provides break and continue
statements. These statements are used to immediately come out of any
loop or to start the next iteration of any loop respectively.
Example
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Information courtesy of TutorialsPoint.com
By changing a bit your logic:
Store Player names into an Array, change turn using 0,1,0,1... numbers,
Use only one prompt!! The current player is defined by players[turnNumber]
var rnd = Math.round( Math.random() * 5), // 0 - 5
res = -1, // Result
pl = [], // ["Ethan", "Roko"]
t = 0; // turn: 0,1,0,1... (0 = 1st player)
for(var i=0; i<2; i++) pl[i] = prompt("Player"+ (i+1) +", please enter your name:");
while (res !== rnd) {
res = parseInt( prompt( pl[t] + ", take a Guess (0-5)"), 10);
alert( res===rnd ? (res +" is correct! "+ pl[t] +" has won!") : (res<rnd? "Higher" : "Lower"));
t = ++t % 2; // increment turn and reset to 0 if === 2 Results in: 1,0,1,0...
}

Categories

Resources