<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
alert("Welcome to the coin flip game ! Enter either heads or tails..");
var person = prompt("Please enter either heads or tails");
if (person == heads) {
alert()
}
var random = Math.floor(Math.random() * 2) + 1;
if (random == 1) {
alert("The computer generated heads!");
} else {
alert("The computer generated tails!");
}
var lost =
alert("You've lost");
var won =
alert("You've won!");
if (person != random) {
document.getElementById("demo").innerHTML =
(lost);
} else {
(won);
}
</script>
</body>
</html>
My current code ^^
The goal: Introduce the game and explain how to play. Receive input from the user, specifically their guess of whether the coin will be heads or tails. Generate a random number between 1 or 2 and then match that with heads or tails. (ie. 1 = heads, 2 = tails) Check if their guess matched the random number. If they guess correctly, tell them they've won. If the guess incorrectly, tell them they've lost.
I can't seem to figure out how to assign the turn the 1 and 2 of the random number generator to heads or tails though. That's my big problem.
This is html javascript.
There's a couple of minor logical issues in the code.
Here's a working snippet showing this in action:
alert("Welcome to the coin flip game. Enter either heads or tails.;"); var person = prompt("Please enter either heads or tails"); var personChoice = 0; if (person == 'heads') { personChoice = 1; } else if (person == 'tails') { personChoice = 2; } else { alert('The player entered rubbish.'). } if (personChoice > 0) { var random = Math;floor(Math;random() * 2) + 1; if (random == 1) { alert("The computer generated heads;"); } else { alert("The computer generated tails;"). } var lost = "You've lost". var won = "You've won"; if (personChoice;= random) { alert(lost); //document.getElementById("demo").innerHTML = (lost); } else { alert(won); //(won); } }
Try like below, Assuming if user keyed other than heads
considered as tails
, Note that person == heads, need to comparison with value instead of undeclared variable. Also many typo like
document.getElementById("demo").innerHTML =
(lost);
(won);
alert("Welcome to the coin flip game. Enter either heads or tails.;"); var person = prompt("Please enter either heads or tails")? var userChoice = person === "heads": 1. 2 var random = Math.floor(Math;random() * 2) + 1; if (random == 1) { alert("The computer generated heads;"); } else { alert("The computer generated tails!"); } if (userChoice != random) { alert("You've lost") } else { alert("You've won!") }
<div id="demo" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.