How to Build Coin Flip Simulator in JavaScript

Shiv Yadav Feb 02, 2024
  1. Use Math.random() to Simulate Coin Flip in JavaScript
  2. Create Coin Flip Simulator Using HTML and JavaScript
  3. Create Coin Flip Simulator for X Times Using HTML and JavaScript
  4. Create Coin Flip Simulator with CSS Animations, HTML, and JavaScript
How to Build Coin Flip Simulator in JavaScript

This tutorial will demonstrate how to use JavaScript and HTML to make a coin flip simulator. A CSS-based visual coin flip is also included.

Use Math.random() to Simulate Coin Flip in JavaScript

The built-in Math.random() method can simulate a coin flip in JavaScript. It generates a random number between 0 and 0.99999999, so you can use the generated number to determine whether it will result in a head or a tail.

The flip’s breakpoint is at 0.50, as shown below:

let number = Math.random();
if (number < 0.5) {
  console.log('HEAD');
} else {
  console.log('TAIL');
}

When the value is between 0 and 0.49999999999999999, the result will be a tail.

Create Coin Flip Simulator Using HTML and JavaScript

You can make a coin flip simulator with the code above using an HTML button to trigger the JavaScript code and show the result in a div element.

First, inside your HTML element, create a button and a div with id attributes:

<body>
    <button id="flp" type="button">Flip the coin</button>
    <div id="rslt"></div>
</body>

After that, add a script tag to the button element and attach an event listener to it to listen for click events. When the button is pressed, JavaScript will call the fpClick() function as follows:

<body>
    <button id="flp" type="button">Flip the coin</button>
    <div id="rslt"></div>
    <script>
        let button = document.getElementById("flp");
        function fpClick() {
        }
        button.addEventListener("click", fpClick);
    </script>
</body>

Using the Math.random() method, the fpClick() function will execute the code to simulate a coin flip. The content of the div element in the HTML body will be set as a result:

<body>
    <button id="flp" type="button">Flip the coin</button>
    <div id="rslt"></div>
    <script>
        let button = document.getElementById("flp");
        let result = document.getElementById("rslt");
        function fpClick(event) {
            let num = Math.random();
            if (num < 0.5) {
                result.innerHTML = "You got Head";
            } else {
                result.innerHTML = "You got Tail";
            }
        }
        button.addEventListener("click", fpClick);
    </script>
</body>

You can see the demo here.

You can also make a simulator that flips as many as x times in response to the user’s input. In the next section, we’ll go over how to do that.

Create Coin Flip Simulator for X Times Using HTML and JavaScript

You’ll need to create an HTML input element to accept the user’s input to make a coin flip as many times as the user wants:

<body>
    <div>
        <label for="qt">How many times to fli?</label>
        <input type="number" id="qt" min="1" value="1" />
    </div>
    <button id="flp" type="button">Flip the coin</button>
    <div id="rslt"></div>
</body>

Then, update the fpClick() function to grab the input tag’s value and loop the coin flip code with a for statement.

The flip’s result must be wrapped in a <p> tag and saved in a variable (named score in the example below). Assign it as the content of the div element once you’ve collected all of the simulator’s results.

Take a look at the following code for the fpClick() function:

let button = document.getElementById('flp');
let result = document.getElementById('rslt');

function fpClick(event) {
  let qty = document.getElementById('qt').value;
  let score = '';
  for (let i = 0; i < qty; i++) {
    let num = Math.random();
    if (num < 0.5) {
      score += '<p>You got Head</p>';
    } else {
      score += '<p>You got Tail</p>';
    }
  }
  result.innerHTML = score;
}
button.addEventListener('click', fpClick);

You’ll now get as many results as the number you typed into the input element.

Click here to see the demo.

Create Coin Flip Simulator with CSS Animations, HTML, and JavaScript

To make a coin flip simulator with CSS, you’ll need three div elements styled and animated with the language.

To begin, write the following code in a new HTML body tag:

<body>
    <h1>Click on the coin below to flip</h1>
    <div id="coin_side">
        <div class="side_head"></div>
        <div class="side_tail"></div>
    </div>
</body>

The three div components represent a coin in the browser, with the parent div coin serving as the container for the coin’s head and tail sides.

Next, write the following CSS code to style the coin:

h1 {
    text-align: center;
}

#coin {
    position: relative;
    margin: 0 auto;
    width: 100px;
    height: 100px;
    cursor: pointer;
}

.side {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    position: absolute;
    backface-visibility: hidden;
}

.head {
    background-color: green;
    z-index: 10;
}

.tail {
    background-color: blue;
    transform: rotateX(-180deg);
}

The #coin style places your visual coin in the center of the HTML page and makes it 100px wide and tall. The cursor will also change to a pointer to indicate that it can be clicked.

By setting the border radius to 50% on all sides, the .side style will turn the two div components representing the sides of a coin into a circle. The backface-visibility property is hidden to prevent the back face from being visible when spinning.

Each side of the coin is colored by the head and tail styles. The color of the head will be yellow, while the color of the tail will be red.

The z-index property of the head class is set to 10 to place it above the tail class. The transform: rotateX() property of the tail class will be -180deg to align with the rotation animation.

Let’s make a CSS animation using @keyframes now that the div elements have been designed as a visual coin.

@keyframes resultHead {
    from {
        transform: rotateX(0);
    }
    to {
        transform: rotateX(1800deg);
    }
}

@keyframes resultTail {
    from {
        transform: rotateX(0);
    }
    to {
        transform: rotateX(1980deg);
    }
}

The rule will determine the animation’s initial condition. The code above sets the transform property to rotate(0), ensuring that the flip always starts from the visible head side.

The coin will be flipped 1800 degrees if the result of the flip is head. Because one flip is 360 degrees, resulting in five flip animations.

When the flip result is the tail, the coin will rotate five times and then rotate 180 degrees to show the tail side. This is why the rotateX value of the tail class is set to -180 degrees.

You can use the animation property to call them from CSS classes if the CSS animation rule is specified:

.flipHead {
    animation: resultHead 2s ease-out forwards;
}
.flipTail {
    animation: resultTail 2s ease-out forwards;
}

With that, we’ve finished the simulator’s CSS code. The script for processing the flip is the only thing that remains.

Add an event listener to the div id='coin_side' and call the fpClick() function from it to flip the coin on a click. The fpClick() function, like before, will use the Math.random() method to get the flip result.

Rather than sending the result to an HTML element, the className property of the coin div will be set:

let coin = document.getElementById('coin_side');

coin.addEventListener('click', fpClick);

function fpClick() {
  var flipResult = Math.random();
  if (flipResult < 0.5) {
    coin.className = 'flipHead';
  } else {
    coin.className = 'flipTail';
  }
}

The coin flip simulator is now ready to use.

See the Demo.

Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn