I am participating in the nuggets Community game creative submission Contest. For details, please see: Game Creative Submission Contest

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

Writing in the front

Remember in just learning DOM, when the use of native JS DOM operation to write a small game on the white block, the game is also very simple, the example effect is as follows:

Ywanzhou.github. IO /white-block…

This small game code is less, suitable for beginners to learn, if not interested, please press [Ctrl/Command+W].

Next, enter the body.

HTML structure

The HTML structure looks like this, with code like this:

<body>
  <! -- Timer and score -->
  <div id="text">
    <h2>Don't step on the white ones</h2>

    <p>Score:<stan id="span">0</stan></p>
  </div>
  <! -- White area in the middle -->
  <div id="container">
    <div class="line"><div></div></div>
  </div>
  <div id="instructions">
    <div class="arrow">
      <div>
        <img class="arrow-img inst-arrow-left" src="./imgs/direction.png" />
      </div>
      <div>
        <img class="arrow-img inst-arrow-down" src="./imgs/direction.png" />
      </div>
      <div>
        <img class="arrow-img inst-arrow-right" src="./imgs/direction.png" />
      </div>
    </div>
  </div>
  <div id="button">
    <button id="gameStart">The game start</button>
    <button id="gameEnd">Game over</button>
  </div>
</body>
Copy the code

Each top-level

above corresponds to a block in the image below, which looks like this:

Then write the corresponding CSS code. In this example, I used the traditional layout method instead of using Flex and Grid. The code is bloated.

Script part

Our implementation idea is mainly through infinite generation of black blocks, and then fall and monitor the event of keyboard press, to achieve the specific steps are as follows:

  • Generating a new black block, creating a new black block outside of the visual effect, is not weird.
  • The black block falls, increases the top value of the black block in the timer, and moves it outside the visual effectElement.remove()Method deleted;
  • The beginning of the game is the continuous generation of black blocks, repeated fall;
  • [Fixed] Stop generating black blocks when the game ends
  • throughkeydownEvent get left, down, right three keys, according to the keys and the latest line of position, match score, otherwise the game ends.

The implementation code is as follows:

// Get the container node
var container = document.getElementById("container")
// Get the body to facilitate binding events
var body = document.body
var span = document.getElementById("span")
function CreBlackBlocks() {
  // Whether the box reaches the bottom of the flag
  this.flag = false
  // Create a new black block method
  this.creBlackBlockLine = function (container) {
    // Create a div node
    var div = document.createElement("div")
    // position, which indicates the row in which the current box is located
    var location
    container.appendChild(div)
    // Randomly assign class attributes to divs
    var random = Math.random()
    if (random <= 0.33) {
      div.setAttribute("class"."test1")
      location = 0
    } else if (random > 0.33 && random <= 0.66) {
      div.setAttribute("class"."test2")
      location = 1
    } else {
      div.setAttribute("class"."test3")
      location = 2
    }
    return {
      // Return an object containing the location and node
      myElement: div,
      myLocation: location,
    }
  }
  this.moveDownward = function (div) {
    // Get a valid attribute
    var divStyles = window.getComputedStyle(div.myElement)
    // Get an inline style sample
    var divStyle = div.myElement.style
    var divStyleTop = parseInt(divStyles.top)
    var t = setInterval(() = > {
      // Inline cover
      divStyleTop++
      divStyle.top = divStyleTop + "px"
      // Delete if the boundary is exceeded
      if (divStyleTop >= 360) {
        clearInterval(t)
        div.myElement.remove()
      }
    }, 1)}}function Game(container) {
  // Store the return value for each row created
  var newDiv
  // Store the created array
  this.divElementArr = []
  // An array of positions for each row
  this.divPosArr = []
  // Use constructor inheritance
  CreBlackBlocks.call(this, container)
  // Score attributes
  this.score = 0
  // start the definition
  this.theGameStartsNow = function (game) {
    var t = setInterval(() = > {
      newDiv = this.creBlackBlockLine(container)
      this.moveDownward(newDiv)
      game.divElementArr.push(newDiv.myElement)
      // Store an array of rows for each square
      game.divPosArr.push(newDiv.myLocation)
      // There is no logic to press the end of the block
      if (parseInt(window.getComputedStyle(this.divElementArr[0]).top) >= 357) {
        game.flag = true
      }
      // End the execution
      if (game.flag == true) {
        clearInterval(t)
        for (div in game.divElementArr) {
          game.divElementArr[div].remove()
        }
        alert("Game over! \n score is:" + game.score)
        game.flag = false
        // Game data initialization
        game.score = 0
        game.divElementArr = []
        game.divPosArr = []
      }
    }, 360)
    return t
  }
  // Define game over
  this.gameOver = function (t, game) {
    for (div in game.divElementArr) {
      game.divElementArr[div].remove()
    }
    clearInterval(t)
    alert("Game over! \n score is:" + game.score)
    // Game data initialization
    game.score = 0
    game.divElementArr = []
    game.divPosArr = []
  }
  // Key click to make corresponding action
  this.keyReaction = function (game, t) {
    body.addEventListener("keydown".function (event) {
      // Use the switch statement to enter the logic based on the current black block position
      The array.splice () method -> removes the elements in the Array and returns an Array with the number of arguments in the first argument
      switch (event.code) {
        case "ArrowLeft":
          game.removeBlock(game, t, 0)
          break
        case "ArrowDown":
          game.removeBlock(game, t, 1)
          break
        case "ArrowRight":
          game.removeBlock(game, t, 2)
          break

        default:
          break}})}this.removeBlock = function (game, t, val) {
    if (game.divPosArr[0] === val) {
      game.divPosArr.splice(0.1)
      game.score += 10
      span.innerHTML = game.score
      game.divElementArr.splice(0.1) [0].remove()
    } else {
      game.gameOver(t, game)
    }
  }
}

var game = new Game(container)
var t
// Start the game
var gameStart = document.getElementById("gameStart")
gameStart.addEventListener("click".function () {
  span.innerHTML = 0
  t = game.theGameStartsNow(game)
  game.keyReaction(game, t)
})
// Game over
var gameEnd = document.getElementById("gameEnd")
gameEnd.addEventListener("click".function () {
  game.gameOver(t, game)
})
Copy the code

That’s all the code for this game.

Write in the last

The code in this article was written when I just learned DOM, and there are some bugs that have not been fixed, so I will rewrite them when I have time.

If you feel garbage code, garbage game please spray.