DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Heads or Tails with JS

Using JavaScript, let's create a heads or tails game with JS

Code

HTML

<fieldset>
  <legend>Cara ou Coroa</legend>
  <div id="cardEl" class="card">
    <div class="front">
      <img src="https://placekitten.com/250/250" alt="head" />
    </div>
    <div class="back">
      <img
           src="https://placekitten.com/g/250/250"
           alt="tail"
           />
    </div>
  </div>
  <div id="resultEl" style="display: none">
    <div>O resultado foi: <strong id="outputEl"></strong></div>
    <div>
      Sorteio realizado em: <strong id="dateEl"></strong> às
      <strong id="timeEl"></strong>
    </div>
  </div>
</fieldset>
Enter fullscreen mode Exit fullscreen mode

This code is an HTML snippet that creates a "Cara ou Coroa" (heads or tails) game using a fieldset element, which is used to group related form controls and labels together. Inside the fieldset, there is a legend element that displays the text "Cara ou Coroa".

The code also creates a div element with the id "cardEl" and class "card", which contains two more div elements with the classes "front" and "back". These div elements are used to display the images of the front and back of a coin. The images are being pulled from the placekitten.com website with an img element.

Lastly, there is a div element with the id "resultEl", which is set to display: none; this element will be used to show the results of the game. The results will include the outcome of the game and the date and time of the game. The outcome is displayed in a strong element with the id "outputEl" and the date and time are displayed in strong elements with the ids "dateEl" and "timeEl", respectively.

JS

'use strict';

cardEl.addEventListener('click', main);

const getRandom = () => Math.floor(Math.random() * 2);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function dateNow() {
  let date = new Date();
  let localeDate = date.toLocaleDateString('pt-BR', { dateStyle: 'long' });
  let localeTime = date.toLocaleTimeString('pt-BR', { timeStyle: 'medium' });
  return { localeDate, localeTime };
}

async function main() {
  resultEl.style.display = 'none';
  cardEl.classList.add('card-active');
  await sleep(3000);
  let result = getRandom() ? 'cara' : 'coroa';

  result == 'cara'
    ? cardEl.classList.remove('back-active')
  : cardEl.classList.add('back-active');

  cardEl.classList.remove('card-active');

  let { localeDate, localeTime } = dateNow();
  dateEl.innerHTML = localeDate;
  timeEl.innerHTML = localeTime;
  outputEl.innerHTML = result;
  resultEl.style.display = 'block';
}
Enter fullscreen mode Exit fullscreen mode

The script starts by setting the 'use strict' statement, which is a way to opt-in to a restricted variant of JavaScript.

Then, an event listener is added to the cardEl element, which listens for a click event. When a click event is detected, the main function is called.

The script defines a function named getRandom() which returns a random number between 0 and 1, this will be used to determine the outcome of the game.

Then, a function named sleep is defined which takes a parameter ms, this function returns a promise that is resolved after the specified amount of milliseconds.

A function named dateNow() is defined to get the current date and time in Brazilian Portuguese format.

The main function is defined as async and when it is called it first sets the display of the resultEl element to none, this will make the result of the game invisible to the user. The class "card-active" is added to the cardEl element, this will be used to add a visual effect to the coin, as it spins. After that, the sleep function is called, it makes the script wait for 3 seconds before continuing.

Then, a variable named result is defined and a random value of either 'cara' or 'coroa' is assigned to it.

Next, the script checks the value of the result variable. If it's 'cara', the class 'back-active' is removed from the cardEl element, otherwise, the class 'back-active' is added to the cardEl element. Then the class 'card-active' is removed from the cardEl element.

Finally, the date and time are obtained by calling the dateNow() function and are assigned to the respective elements. The value of the result variable is assigned to the outputEl element and the display of the resultEl element is set to block, this will make the result of the game visible to the user.

Demo

See below for the complete working project.

💡 NOTE: If you can't see it click here and see the final result


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)