码迷,mamicode.com
首页 > Web开发 > 详细

JS实现一个基本的打地鼠游戏

时间:2016-10-29 19:29:15      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:round   sed   extc   struct   bind   get   amp   dex   last   

直入正题,用JS实现一个简单的打地鼠游戏

因为功能比较简单就直接裸奔JS了,先看看效果图,或者 在线玩玩 吧 

技术分享

如果点击颜色比较深的那个(俗称坏老鼠),将扣分50;如果点击颜色比较浅的那个(俗称好老鼠),将得分100

 

实现

老鼠好像有点难画,又不想用图片,就直接用CSS画个简单的图代表老鼠和坑吧

html结构

挺简单,用9个 li 标签代表坑,用9个 div 标签代表老鼠

  <div class="container">
        <h4>无聊打打地鼠</h4>

        <div class="game-top">
            <p><input type="button" value="开始游戏" id="game-start"><p>
            <p>得分:<span id="game-score">0</span></p>
            <p>剩余时间:<span id="game-time">60</span> s</p>
        </div>
        <div class="game-content">
            <ul>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
                <li><div></div></li>
            </ul>
        </div>
    </div>

CSS的实现

有点小技巧

对于坑,加个box-shadow: ... inset 美化一下样式

        .game-content li {
            float: left;
            margin-top: 50px;
            margin-left: 30px;
            width: 100px;
            height: 50px;
            border-radius: 50%;
            background-color: #67d0b4;
            box-shadow: 0 0 50px #706565 inset;
        }

对于老鼠,用 border-radius:50%/40% 绘制,第二个参数还是有点使用价值的

        .game-content div {
            position: relative;
            margin-top: -15px;
            margin-left: 25px;
            width: 50px;
            height: 70px;
            border-radius: 50%/40%;
            background-color: #dfb25d;
            opacity: 0;
        }

而要让老鼠动起来,这里的处理方式就是用动画了,老鼠运动的时候,先往上再往下即可,控制好相对位置看起来和谐一点就行

        @keyframes mouse-move {
            50% {
                margin-top: -40px;
                opacity: 1;
            }
            100% {
                margin-top: -15px;
                opacity: 0;
            }
        }
        .game-content div.active {
            animation: mouse-move 2s ease-in-out infinite;
        }

注意 animation: ... infinite 的使用,让动画能一直进行下去,我们使用JS控制好时间差判断应该显示那个老鼠,应该显示多少只老鼠即可

不然的画,会发现动画完成了再也无法让它继续进行了

技术分享
 1         <style type="text/css">
 2         .container {
 3             width: 500px;
 4             height: 300px;
 5             margin: 50px auto;
 6             border: 1px solid #ddd;
 7             text-align: center;
 8         }
 9         .game-top {
10             padding-top: 10px;
11             width: 100%;
12             height: 90px;
13         }
14         .game-top p {
15             margin: 5px;
16         }
17         .game-content {
18             overflow: auto;
19             width: 100%;
20             border-top: 1px solid #ddd;
21             background-color: #ddf;
22         }
23         .game-content ul {
24             list-style: none;
25         }
26         .game-content li {
27             float: left;
28             margin-top: 50px;
29             margin-left: 30px;
30             width: 100px;
31             height: 50px;
32             border-radius: 50%;
33             background-color: #67d0b4;
34             box-shadow: 0 0 50px #706565 inset;
35         }
36         .game-content li:last-child {
37             margin-bottom: 50px;
38         }
39         .game-content div {
40             position: relative;
41             margin-top: -15px;
42             margin-left: 25px;
43             width: 50px;
44             height: 70px;
45             border-radius: 50%/40%;
46             background-color: #dfb25d;
47             opacity: 0;
48         }
49         .game-content div.good {
50             background-color: #dfb25d;
51         }
52         .game-content div.bad {
53             background-color: #a48f5c;
54         }
55         @keyframes mouse-move {
56             50% {
57                 margin-top: -40px;
58                 opacity: 1;
59             }
60             100% {
61                 margin-top: -15px;
62                 opacity: 0;
63             }
64         }
65         .game-content div.active {
66             animation: mouse-move 2s ease-in-out infinite;
67         }
68     </style>
完整CSS

 

JS的处理

逻辑是点击开始游戏,倒计时开始,同时好坏老鼠不断运动,控制好坑中好坏老鼠及其数量的随机性,点击好老鼠加分,点击坏老鼠减分,时间到结束游戏。

先看看老鼠的运动

            // 运动操作
            moveUpAndDown: function() {
                var that = this;

                // 定时器随机定义good|bad老鼠个数,以及需要显示的个数
                that.moveTime = setInterval(function() {

                    for (var i = 0, j = that.mouses.length; i < j; ++i) {
                        that.mouses[i].setAttribute(‘clicked‘, ‘0‘);
                        that.mouses[i].className = ‘good active‘;
                        that.mouses[i].style.display = ‘none‘;
                    }

                    // bad 的个数
                    for (var i = 0; i < that.getRandom(0, 8); i++) {
                        that.mouses[that.getRandom(0, 8)].className = ‘bad active‘;
                    }

                    // 要显示的个数
                    for (var i = 0; i < that.getRandom(0, 8); i++) {
                        that.mouses[that.getRandom(0, 8)].style.display = ‘block‘;
                    }
                }, 2000);
            },

使用定时器,定时器的循环与CSS中的动画设置一致,保证循环连贯性

设置class为good 即可定义出一只好老鼠,同理bad 为坏老鼠

在开始游戏,进行调用时,设置class为active 即可让老鼠运动起来

对于打老鼠的操作,要注意到只有运动的老鼠才能点击,每只老鼠只能点击一次

              // 打地鼠操作
                that.mousesWrap[0].addEventListener(‘click‘, function(e) {
                    e = e || window.event;
                    var elem = e.target || e.srcElement;
                    // 如果当前项被隐藏则不操作,多次点击只取第一次分数
                    if (elem.style.display !== ‘block‘ || elem.getAttribute(‘clicked‘) === ‘1‘) {
                        return;
                    }
                    // 扣分
                    if (elem.className.indexOf(‘bad‘) !== -1) {
                        that.score -= that.badScore;
                    }
                    // 加分
                    else {
                        that.score += that.goodScore;
                    }

                    elem.setAttribute(‘clicked‘, ‘1‘);
                    that.text(that.gameScore[0], that.score);
                }, false);

倒计时结束之后,清除两个计时器,同时将所有老鼠项display都设为none 即可(否则动画会一直循环展示出来)

            // 倒计时,当前剩余游戏时间
            countDown: function() {
                var that = this;

                var t = setInterval(function() {
                    that.text(that.gameTime[0], --that.totalTime);

                    if (that.totalTime === 0) {
                        clearInterval(t);
                        clearInterval(that.moveTime);

                        for (var i = 0, j = that.mouses.length; i < j; ++i) {
                            that.mouses[i].style.display = ‘none‘;
                        }

                        alert(‘游戏结束,得分为:‘ + that.score);
                    }
                }, 1000);
            },
技术分享
  1     <script type="text/javascript">
  2 
  3         function MouseGame() {
  4             this.mousesWrap = this.$(‘.game-content‘);
  5             this.mouses = this.$(‘.game-content div‘);
  6             this.gameStart = this.$(‘#game-start‘);
  7             this.gameTime = this.$(‘#game-time‘);
  8             this.gameScore = this.$(‘#game-score‘);
  9             this.goodScore = 100;
 10             this.badScore = 50;
 11 
 12             this.bindEvent();
 13         }
 14 
 15         MouseGame.prototype = {
 16             constructor: MouseGame,
 17 
 18             /**
 19              * 获取元素
 20              * @param  {String} elem 元素的字符串标识
 21              * @example
 22              * $(‘div‘) | $(‘p.active‘)
 23              * @return {NodeList}      获取的元素集
 24              */
 25             $: function(elem) {
 26                 return document.querySelectorAll(elem);
 27             },
 28 
 29             /**
 30              * 获取给定范围的随机数
 31              * @param  {Number} from 起始
 32              * @param  {Number} to   结束
 33              * @return {Number}      随机数
 34              */
 35             getRandom: function(from, to) {
 36                 return Math.floor(Math.random() * (to - from + 1)) + from;
 37             },
 38 
 39             /**
 40              * 设置元素内容
 41              * @param  {HTMLElement} elem 要设置的元素
 42              * @param  {String} val  设置的内容
 43              * @return {String}      设置好的内容|元素本身的内容
 44              */
 45             text: function(elem, val) {
 46                 if (elem.textContent) {
 47                     return val !== undefined ? elem.textContent = val : elem.textContent;
 48                 } else if (elem.innerText) {
 49                     return val !== undefined ? elem.innerText = val : elem.innerText;
 50                 }
 51             },
 52 
 53             // 运动操作
 54             moveUpAndDown: function() {
 55                 var that = this;
 56 
 57                 // 定时器随机定义good|bad老鼠个数,以及需要显示的个数
 58                 that.moveTime = setInterval(function() {
 59 
 60                     for (var i = 0, j = that.mouses.length; i < j; ++i) {
 61                         that.mouses[i].setAttribute(‘clicked‘, ‘0‘);
 62                         that.mouses[i].className = ‘good active‘;
 63                         that.mouses[i].style.display = ‘none‘;
 64                     }
 65 
 66                     // bad 的个数
 67                     for (var i = 0; i < that.getRandom(0, 8); i++) {
 68                         that.mouses[that.getRandom(0, 8)].className = ‘bad active‘;
 69                     }
 70 
 71                     // 要显示的个数
 72                     for (var i = 0; i < that.getRandom(0, 8); i++) {
 73                         that.mouses[that.getRandom(0, 8)].style.display = ‘block‘;
 74                     }
 75                 }, 2000);
 76             },
 77 
 78             // 打地鼠操作
 79             bindEvent: function() {
 80                 var that = this;
 81 
 82                 // 监听游戏开始/重新开始
 83                 that.gameStart[0].addEventListener(‘click‘, function() {
 84                     that.startGame();
 85                 }, false);
 86 
 87                 // 打地鼠操作
 88                 that.mousesWrap[0].addEventListener(‘click‘, function(e) {
 89                     e = e || window.event;
 90                     var elem = e.target || e.srcElement;
 91                     // 如果当前项被隐藏则不操作,多次点击只取第一次分数
 92                     if (elem.style.display !== ‘block‘ || elem.getAttribute(‘clicked‘) === ‘1‘) {
 93                         return;
 94                     }
 95                     // 扣分
 96                     if (elem.className.indexOf(‘bad‘) !== -1) {
 97                         that.score -= that.badScore;
 98                     }
 99                     // 加分
100                     else {
101                         that.score += that.goodScore;
102                     }
103 
104                     elem.setAttribute(‘clicked‘, ‘1‘);
105                     that.text(that.gameScore[0], that.score);
106                 }, false);
107             },
108 
109             // 倒计时,当前剩余游戏时间
110             countDown: function() {
111                 var that = this;
112 
113                 var t = setInterval(function() {
114                     that.text(that.gameTime[0], --that.totalTime);
115 
116                     if (that.totalTime === 0) {
117                         clearInterval(t);
118                         clearInterval(that.moveTime);
119 
120                         for (var i = 0, j = that.mouses.length; i < j; ++i) {
121                             that.mouses[i].style.display = ‘none‘;
122                         }
123 
124                         alert(‘游戏结束,得分为:‘ + that.score);
125                     }
126                 }, 1000);
127             },
128 
129             // 开始游戏
130             startGame: function() {
131                 this.score = 0;
132                 this.totalTime = 60;
133                 this.text(this.gameTime[0], this.totalTime);
134                 this.text(this.gameScore[0], this.score);
135 
136                 this.countDown();
137                 this.moveUpAndDown();
138             }
139         };
140 
141         new MouseGame();
142     </script>
完整JS

 

代码有注释应该不难看懂了

那么..快来fork吧..

JS实现一个基本的打地鼠游戏

标签:round   sed   extc   struct   bind   get   amp   dex   last   

原文地址:http://www.cnblogs.com/imwtr/p/6011407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!