Day30 - JS Implementing Hamster Play

This article is from: Chunge Personal Blog: http://www.liyuechun.org
Author: extension Li Yuechun - A Time-chasing Man
Introduction: JavaScript30 yes Wes Bos A 30-day challenge to launch. The project provides 30 video tutorials, 30 challenge start documents and 30 challenge solution source code free of charge. The goal is to help people write in pure JavaScript, without using frameworks and libraries or compilers and references. Now you see the 30th in this series of guidelines. The complete Chinese version of the guide and video tutorial in From Zero to Yiquantan Tribe.

Design sketch

On-line rendering

On the 30th day, the challenge is to hit the hamster game through JS, click the start button, and the hamster appears randomly in six holes. The hamster will gain one point if it hits the hamster.

HTML code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Whack A Mole!</title>
  <link href='https://fonts.googleapis.com/css?family=Amatic+SC:400,700' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="style.css">
</head>

<body>

  <h1>Whack-a-mole! <span class="score">0</span></h1>
  <button onClick="startGame()">Start!</button>

  <div class="game">
    <div class="hole hole1">
      <div class="mole"></div>
    </div>
    <div class="hole hole2">
      <div class="mole"></div>
    </div>
    <div class="hole hole3">
      <div class="mole"></div>
    </div>
    <div class="hole hole4">
      <div class="mole"></div>
    </div>
    <div class="hole hole5">
      <div class="mole"></div>
    </div>
    <div class="hole hole6">
      <div class="mole"></div>
    </div>
  </div>

</body>
</html>
  • The button to start the game
 <button onClick="startGame()">Start!</button>
  • Show scores
<h1>Whack-a-mole! <span class="score">0</span></h1>
  • Burrows, hamsters
<div class="game">
    <div class="hole hole1">
        <div class="mole"></div>
    </div>
    <div class="hole hole2">
        <div class="mole"></div>
    </div>
    <div class="hole hole3">
        <div class="mole"></div>
    </div>
    <div class="hole hole4">
        <div class="mole"></div>
    </div>
    <div class="hole hole5">
        <div class="mole"></div>
    </div>
    <div class="hole hole6">
        <div class="mole"></div>
    </div>
</div>

hole is a burrow with a rat mole in it.

CSS code

html {
  box-sizing: border-box;
  font-size: 10px;
  background: #ffc600;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  padding: 0;
  margin: 0;
  font-family: 'Amatic SC', cursive;
}

h1 {
  text-align: center;
  font-size: 10rem;
  line-height: 1;
  margin-bottom: 0;
}

.score {
  background: rgba(255, 255, 255, 0.2);
  padding: 0 3rem;
  line-height: 1;
  border-radius: 1rem;
}

.game {
  width: 600px;
  height: 400px;
  display: flex;
  flex-wrap: wrap;
  margin: 0 auto;
}

.hole {
  flex: 1 0 33.33%;
  overflow: hidden;
  position: relative;
}

.hole:after {
  display: block;
  background: url(dirt.svg) bottom center no-repeat;
  background-size: contain;
  content: '';
  width: 100%;
  height: 70px;
  position: absolute;
  z-index: 2;
  bottom: -30px;
}

.mole {
  background: url('mole.svg') bottom center no-repeat;
  background-size: 60%;
  position: absolute;
  top: 100%;
  width: 100%;
  height: 100%;
  transition: all 0.4s;
}

.hole.up .mole {
  top: 0;
}
  • dirt.svg is a picture of the underground cave

  • mole.svg is a picture of hamster

JS code

  <script>
    const holes = document.querySelectorAll('.hole');
    const scoreBoard = document.querySelector('.score');
    const moles = document.querySelectorAll('.mole');
    let lastHole;
    let timeUp = false;
    let score = 0;

    function randomTime(min, max) {
      return Math.round(Math.random() * (max - min) + min);
    }

    function randomHole(holes) {
      const idx = Math.floor(Math.random() * holes.length);
      const hole = holes[idx];
      if (hole === lastHole) {
        console.log('Ah nah thats the same one bud');
        return randomHole(holes);
      }
      lastHole = hole;
      return hole;
    }

    function peep() {
      const time = randomTime(200, 1000);
      const hole = randomHole(holes);
      hole.classList.add('up');
      setTimeout(() => {
        hole.classList.remove('up');
        if (!timeUp) peep();
      }, time);
    }

    function startGame() {
      scoreBoard.textContent = 0;
      timeUp = false;
      score = 0;
      peep();
      setTimeout(() => timeUp = true, 10000)
    }

    function bonk(e) {
      if (!e.isTrusted) return; // cheater!
      score++;
      this.parentNode.classList.remove('up');
      scoreBoard.textContent = score;
    }

    moles.forEach(mole => mole.addEventListener('click', bonk));
  </script>
  • Get all the holes, scores, mouse sticks
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
  • initialize variable
let lastHole; //Used to store the last underground cave, mainly for comparison with the next one.
let timeUp = false; //Judge whether the time is over
let score = 0; //Record score
  • event listeners
<!--Hit the hamster, call bonk Method-->
moles.forEach(mole => mole.addEventListener('click', bonk));
  • isTrusted attribute
function bonk(e) {
     if (!e.isTrusted) return; // Judgment is not operator operation, not code program operation!?
     score++; // Kick a goal
     this.parentNode.classList.remove('up'); // Concealed hamster
     scoreBoard.textContent = score; //Update score
}

Event.isTrusted

The isTrusted read-only property of the Event interface is a Boolean value. If the event object is generated by the user's operation, the isTrusted value is true. If the event object is created, modified, or triggered by EventTarget.dispatchEvent(), the isTrusted value is false.

  • Start the game
function startGame() {
    scoreBoard.textContent = 0; //Empty score
    timeUp = false; //Set the time end flag to false
    score = 0; //Score zero
    peep(); //Call peep() function
    setTimeout(() => timeUp = true, 10000) //Setting countdown
}
  • Random Time sets a random number between min - max

Math.round

Math.round( 20.49); //  20
Math.round( 20.5);  //  21
Math.round( 42  );  //  42
Math.round(-20.5);  // -20
Math.round(-20.51); // -21
function randomTime(min, max) {
    //The Math.round() function returns the nearest integer value after rounding a number.
    //The Math.random() function returns a floating point with pseudorandom numbers in the range [0, 1], and then you can zoom in to the desired range.
    return Math.round(Math.random() * (max - min) + min);
}
  • Random Hole function

Math.floor

Math.floor( 45.95); //  45
Math.floor( 45.05); //  45
Math.floor(  4   ); //   4
Math.floor(-45.05); // -46 
Math.floor(-45.95); // -46
//Random selection of a ground hole for the ejection of hamsters
function randomHole(holes) {
    //Math.floor() returns the largest integer less than or equal to a given number.
    const idx = Math.floor(Math.random() * holes.length);
    const hole = holes[idx];
    if (hole === lastHole) {
        console.log('Ah nah thats the same one bud');
        return randomHole(holes);
    }
    lastHole = hole;
    return hole;
}
  • peep() function
// Hamster and Ground Hole Processing Function
function peep() {
    //Generate a random number, which is used to set when the current hamster disappears
    const time = randomTime(200, 1000);
    //Random generation of a value of 0 - 5 for random selection of a tunnel
    const hole = randomHole(holes);
    //Pop rat
    hole.classList.add('up');
    //Hamsters disappear after time
    setTimeout(() => {
        hole.classList.remove('up');
        //If the countdown does not arrive, continue calling the peep() function
        if (!timeUp) 
            peep();
    }, time);
}

Source download

Github Source Code

Keywords: Javascript Attribute less github

Added by robert_gsfame on Tue, 04 Jun 2019 21:09:53 +0300