返回

中秋限定大作!jQuery捉拿中秋打地鼠月饼!

前端

中秋限定大作!jQuery捉拿中秋打地鼠月饼!

码上掘金挑战赛来了!作为今年的第一个活动,还是很有意思的,但是像我这种存货不多的,就只能水水文章了。

游戏逻辑

打地鼠

游戏过程

点击任意一个地洞,月饼随机出现,点击月饼加一分,错失或点击地洞扣一分。

游戏规则

  1. 每次出现一个地洞,随机出现月饼,点击月饼得一分,点击地洞扣一分。
  2. 游戏时间为 60 秒。
  3. 游戏结束时,得分最高者获胜。

游戏效果

游戏源码

<!DOCTYPE html>
<html>
<head>
  
  <style>
    body {
      background-color: #ffe6cc;
    }
    .container {
      width: 100%;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .game {
      width: 600px;
      height: 600px;
      background-color: #ffffff;
      border: 1px solid #000000;
    }
    .hole {
      width: 100px;
      height: 100px;
      background-color: #000000;
      border: 1px solid #ffffff;
      float: left;
      margin: 10px;
      cursor: pointer;
    }
    .mooncake {
      width: 50px;
      height: 50px;
      background-color: #ff9900;
      border: 1px solid #ffffff;
      position: absolute;
      top: 0;
      left: 0;
      display: none;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="game">
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
      <div class="hole"></div>
    </div>
  </div>

  <script src="jquery.min.js"></script>
  <script>
    $(function() {
      var game = {
        holes: [],
        mooncake: null,
        score: 0,
        timer: null,
        init: function() {
          this.holes = $('.hole');
          this.mooncake = $('.mooncake');
          this.score = 0;
          this.timer = null;
          this.bindEvents();
        },
        bindEvents: function() {
          var self = this;
          this.holes.on('click', function() {
            if (self.mooncake.is(':visible')) {
              self.score++;
            } else {
              self.score--;
            }
            self.updateScore();
          });
        },
        updateScore: function() {
          $('#score').text(this.score);
        },
        start: function() {
          this.timer = setInterval(function() {
            var hole = self.holes.eq(Math.floor(Math.random() * self.holes.length));
            self.mooncake.css({
              top: hole.offset().top,
              left: hole.offset().left
            }).show();
            setTimeout(function() {
              self.mooncake.hide();
            }, 500);
          }, 500);
        },
        stop: function() {
          clearInterval(this.timer);
        }
      };

      game.init();
      game.start();
    });
  </script>
</body>
</html>

总结

本次复刻使用jQuery重制了中秋限定版本《打地鼠》,小伙伴们可以自己动手实现一下,还是很有意思的。