Write a small game of don't step on white blocks to learn about the native DOM

I am participating in the individual competition of the Nuggets Community Game Creative Contest. For details, please see:Game Creative Contest

Hi everybody, I'mone bowl week, a front end that doesn't want to be drunk (involuted). If the article written is fortunate enough to get your favor, I am very fortunate~

write in front

I remember when I was just learning the DOM, I used native JS to manipulate the DOM and wrote a small game about not stepping on white blocks. The game is also very simple. The example effect is as follows:

demo.gif

online experience:ywanzhou.github.io/white-block…

The code of this small game is relatively small, which is suitable for beginners to learn. If you are not interested, please press [Ctrl/Command+W] .

Next to the text.

HTML structure

The HTML structure is as follows, the code is as follows:

<body>
  <!-- 计时器和分数 -->
  <div id="text">
    <h2>别踩白块儿</h2>

    <p>分数 : <stan id="span">0</stan></p>
  </div>
  <!-- 中间白块区域 -->
  <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">游戏开始</button>
    <button id="gameEnd">游戏结束</button>
  </div>
</body>
复制代码

Each top level above <div>corresponds to a block in the following diagram, which is as follows:

Analysis page.png

Then write the corresponding CSS code. In this example, I use the traditional layout method, and do not use Flex and Grid. The code implemented is bloated.

script section

Our implementation idea is mainly to generate black blocks indefinitely, then fall and monitor the events of the keyboard press, and realize the implementation. The specific steps are as follows:

  • Generate a new black block, and generate a new black block outside the visual effect, so it doesn't look very strange;
  • When the black block falls, increase the top value of the black block in the timer, move it outside the visual effect, and Element.remove()delete it through the method;
  • The game starts with the continuous generation of black blocks and repeated falling;
  • Stop the generation of black blocks when the game is over;
  • Get the left, down, and right three buttons through the keydownevent, and match the score according to the position of the button and the latest row, otherwise the game is over.

The implementation code is as follows:

// 获取容器节点
var container = document.getElementById("container")
// 获取body 方便绑定事件
var body = document.body
var span = document.getElementById("span")
function CreBlackBlocks() {
  // 方块是否到达底部的标志
  this.flag = false
  // 创建一个新的黑块的方法
  this.creBlackBlockLine = function (container) {
    // 创建 div 节点
    var div = document.createElement("div")
    // 位置,表示当前方块在第几行
    var location
    container.appendChild(div)
    // 随机为 div 分配 class 属性
    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 {
      // 返回一个对象,包含位置和节点
      myElement: div,
      myLocation: location,
    }
  }
  this.moveDownward = function (div) {
    // 获取有效属性
    var divStyles = window.getComputedStyle(div.myElement)
    // 获取内联样式样
    var divStyle = div.myElement.style
    var divStyleTop = parseInt(divStyles.top)
    var t = setInterval(() => {
      // 内联盖外联
      divStyleTop++
      divStyle.top = divStyleTop + "px"
      // 越界则删除
      if (divStyleTop >= 360) {
        clearInterval(t)
        div.myElement.remove()
      }
    }, 1)
  }
}
function Game(container) {
  // 存储创建每一行的返回值
  var newDiv
  // 存储创建的数组
  this.divElementArr = []
  // 每一行位置的数组
  this.divPosArr = []
  // 借助构造函数继承
  CreBlackBlocks.call(this, container)
  // 分数属性
  this.score = 0
  // 定义定义开始
  this.theGameStartsNow = function (game) {
    var t = setInterval(() => {
      newDiv = this.creBlackBlockLine(container)
      this.moveDownward(newDiv)
      game.divElementArr.push(newDiv.myElement)
      // 存储每一个方块第几行的数组
      game.divPosArr.push(newDiv.myLocation)
      // 没有按到方块结束的逻辑
      if (parseInt(window.getComputedStyle(this.divElementArr[0]).top) >= 357) {
        game.flag = true
      }
      // 结束执行的行为
      if (game.flag == true) {
        clearInterval(t)
        for (div in game.divElementArr) {
          game.divElementArr[div].remove()
        }
        alert("游戏结束!\n分数为:" + game.score)
        game.flag = false
        // 游戏数据初始化
        game.score = 0
        game.divElementArr = []
        game.divPosArr = []
      }
    }, 360)
    return t
  }
  // 定义游戏结束
  this.gameOver = function (t, game) {
    for (div in game.divElementArr) {
      game.divElementArr[div].remove()
    }
    clearInterval(t)
    alert("游戏结束!\n分数为:" + game.score)
    // 游戏数据初始化
    game.score = 0
    game.divElementArr = []
    game.divPosArr = []
  }
  // 键位点击做出相应的动作
  this.keyReaction = function (game, t) {
    body.addEventListener("keydown", function (event) {
      // 通过 switch 语句 根据当前的黑块的位置进入逻辑
      // Array.splice()方法 -> 作用,删除中的元素并返回一个数组,第一个参数 位置第二个参数数量
      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
// 游戏开始
var gameStart = document.getElementById("gameStart")
gameStart.addEventListener("click", function () {
  span.innerHTML = 0
  t = game.theGameStartsNow(game)
  game.keyReaction(game, t)
})
// 游戏结束
var gameEnd = document.getElementById("gameEnd")
gameEnd.addEventListener("click", function () {
  game.gameOver(t, game)
})
复制代码

That's all the code for this game.

write at the end

The code in the article was written when I was just learning DOM, and some bugs have not been fixed yet. I will rewrite it later when I have time.

If you feel that the code is garbage or game garbage, please spray lightly.

Guess you like

Origin juejin.im/post/7079414945493811207