<script>/*一个人守着一棵树,各种动物会来撞树,其中80%的概率出现的是兔子,20%的概率出现的是老虎。兔子撞树后,60%的概率兔子撞晕了,人直接捡到兔子,40%的概率兔子没撞晕,人有50%的概率抓到活兔子老虎撞树后,30%的概率老虎撞晕了,人直接捡到老虎。70%概率老虎没撞晕。对于没撞晕的老虎,人有30%的概率打死老虎,捡到老虎。40%的概率没打死老虎,老虎跑掉。还有30%的概率人被老虎咬死了,这时游戏结束。*/function Rabbit(){this.name = "rabbit";this.isyun = false;this.hitTree = function(){var random = Math.random();if(random < 0.6){this.isyun = true;}};this.toString = function(){return this.name;}}function Tiger(){this.name = "tiger";this.isyun = false;this.hitTree = function(){var random = Math.random();if(random < 0.3){this.isyun = true;}}this.toString = function(){return this.name;}}function Person(){//数组this.lanzi = [];this.isdead = false;this.name = "武松";this.doWithAnimal = function(animal){//如果动物晕掉了,直接捡起来if(animal.isyun == true){console.log(this.name+"捡起了"+animal.name);this.lanzi.push(animal);}//如果动物没有晕,我们得区分这个动物是兔子还是老虎else{var random = Math.random();//如果这个没晕的动物是兔子if(animal instanceof Rabbit){if(random < 0.5){console.log(this.name+"抓到了活的"+animal.name);this.lanzi.push(animal);}else{console.log(animal.name+"跑掉了");}}//如果这个没晕的动物是老虎else{if(random < 0.3){console.log(this.name+"打死了"+animal.name);this.lanzi.push(animal);}else if(random < 0.7){console.log(animal.name+"跑掉了");}else{console.log(this.name+"被"+animal.name+"咬死了");this.isdead = true;}}}}}//创建一个人的对象var p = new Person();//模拟10次动物来撞树for (var i = 0; i < 10; i++) {var r = null;if(Math.random()<0.8){//兔子r = new Rabbit();}else{//老虎r = new Tiger();}//计算机是如何确定究竟该调用兔子的hitTree还是老虎的hitTree//js是动态类型的语言r.hitTree();//引用传递 : 好处当前的全局执行环境的中r和Person对象中doWithAnimal()方法中的animal是同一个东西p.doWithAnimal(r);//人死了if(p.isdead == true){console.log("GAME OVER");break;}}if(p.isdead == false){console.log("今天好开心了,好多动物啊"+p.lanzi);}</script>

