首页 > 其他 > 详细

关灯游戏

时间:2019-08-27 21:29:25      阅读:93      评论:0      收藏:0      [点我收藏+]

<!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>

关灯游戏

原文:https://www.cnblogs.com/Deep-dark/p/11420784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!