关灯游戏

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Docunment</title>
</head>
<body>
  <script type="text/javascript">
    const Lightwidth = 50
    const Lightheight = 50
    const Rowcount = 10
    const Colcount = 10
    const Oncolor = 'yellow'
    const Offcolor = 'black'

    gameInit()

    function gameInit() {
      let wrapper = document.createElement('div')
      wrapper.style.width = Lightwidth * Colcount + 'px'
      wrapper.style.height = Lightheight * Rowcount + 'px'
      document.body.appendChild(wrapper)

      for (let i = 1; i <= Colcount * Rowcount; i++) {
        let light = document.createElement('div')
        light.id = i
        light.style.boxSizing = 'border-box'
        light.style.border = '1px solid gray'
        light.style.width = Lightwidth + 'px'
        light.style.height = Lightheight + 'px'
        light.style.backgroundColor = Offcolor
        light.style.float = 'left'
        light.onclick = lightClick

        wrapper.appendChild(light)
      }
    }

    function lightClick(light) {
      turnLight(this)
      // 找到上下左右的灯
      let aList = getAroundList(this)
      for (let i = 0; i < aList.length; i++) {
        turnLight(aList[i])
      }
    }

    function getAroundList(light) {
      let offsetList = [1, -1, Colcount, -Colcount]
      let aList = []
      for (let i = 0; i < offsetList.length; i++) {
        let newID = parseInt(light.id) + offsetList[i]
        if (verifyId(light.id, newID)) {
          aList.push(document.getElementById(newID))
        }
      }
      return aList
    }

    // 校验灯的有效性
    function verifyId(id1, id2) {
      if (id1 > 1 && id1 <= Rowcount * Colcount && id2 > 2 && id2 <= Rowcount * Colcount) {
        if (Math.abs(id1 - id2) == 1) {
          // 说明两个灯是左右关系 如果不是同一行就有问题了
          let row1 = Math.ceil(id1 / Colcount)
          let row2 = Math.ceil(id2 / Colcount)
          return row1 == row2
        }
        return true
      }
      return false
    }

    function turnLight(light) {
      if (light.style.backgroundColor != Oncolor) {
        light.style.backgroundColor = Oncolor
      }else{
        light.style.backgroundColor = Offcolor
      }
    }


  </script>

</body>
</html>

上一篇:Games101 计算机图形学课程笔记:Lecture 19 Cameras, Lenses and Light Fields


下一篇:电商API——淘宝拍立淘