M7 IA1 Task1 Exercise3 Irene Arroyo

In this exercise we have to create a game called ‘ Heads or Tails ‘, which implies a coin flipped 3 times and 2 players, one is heads and the other one is tails. Wins the player who have more times ‘heads’ or ‘tails’ on the 3 flip round.

This program requires a control flow, 2 prompts that ask the names of the two players, a loop, I decided to do it with the for loop for the coin flips, and an if else statement to define who won, based on how many times heads have appeared.

Code

<html>
<head>
<script>
let nameHead = prompt (‘What is the name of the heads player?’)
let nameTail = prompt (‘What is the name of the tails player?’)

let headThrows = 0;
let tailThrows = 0; ;

for ( let i = 0; i<3; i++)

{ let coin = (Math.floor(Math.random() * 2));

if ( coin === 1) { headThrows++;
alert ( ‘Player ‘ + nameHead + ‘ has won ‘ + headThrows);}

else { tailThrows++;
alert (‘Player ‘ + nameTail + ‘ has won ‘ + tailThrows); }
}

if (headThrows< 2) { alert (‘Congratulations ‘ + nameTail + ‘! Tails win!’) }
else {alert ( ‘Congratulations ‘ + nameHead + ‘! Heads win!’); }

</script>
</head>
<body>
</body>
</html>

Exercise 3 | Heads or Tails