Ok so am new to Javascript and am trying to learn. I know this is lengthy, but I would appreciate any help. This is the problem I am working on:
Coin Flip Game
Begin you application by creating a variable called coinFlip and set it equal to a random number using the Math method.
Prompt the user to select "Heads or Tails" and set the result to a new variable called "choice".
Use a conditional to check the result of the coin flip. If it's less than a certain number, it will be heads. If it is greater than a certain number, it will be tails.
If the result is heads and the user selects heads, display the following message within an alert "The flip was heads and you chose heads...you win!".
If the result is heads and the user selects tails, display the following message within an alert: "The flip was heads but you chose tails...you lose!"
If the result is tails and the user selects heads, display the following message within an alert box: "The flip was tails but you chose heads...you lose!"
If the result is tails and the user selects tails, display the following message within an alert: "The flip was tails and you chose tails...you win!"
This is my code so far: (I feel like I am going down the wrong path)
var coinFlip = Math.random();
var coinFlip = prompt("Heads or Tails?");
var coinFlip = var choice;
var choice = Math.random();
You just need to read each bit carefully. Here's how I'd do it:
1 . Begin you application by creating a variable called coinFlip and set it equal to a random number using the Math method.
For this, I would get a random number between 1
and 2
like so:
var coinFlip = Math.round(Math.random()) + 1;
Here's how I'd solve that:
var choice = prompt("Heads or Tails");
Here I'd just use an if-else
statement like so:
if (coinFlip == 1) {
var flipResult = "heads";
} else {
var flipResult = "tails";
}
4-7. All the win/loss if-else
statements:
if (flipResult == choice) {
if (flipResult == "heads") {
alert("The flip was heads and you chose heads...you win!");
} else {
alert("The flip was tails and you chose tails...you win!");
}
} else {
if (flipResult == "heads") {
alert("The flip was heads and you chose tails...you lose!");
} else {
alert("The flip was tails and you chose heads...you lose!");
}
}
Hopefully this helps!
Note: you must enter either "heads" or "tails" in the prompt (case-sensitive) for the code to work.