溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么用html5實(shí)現(xiàn)蘑菇與熊游戲

發(fā)布時(shí)間:2021-11-18 13:31:15 來源:億速云 閱讀:132 作者:iii 欄目:web開發(fā)

這篇文章主要講解了“怎么用html5實(shí)現(xiàn)蘑菇與熊游戲”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么用html5實(shí)現(xiàn)蘑菇與熊游戲”吧!

一、添加開始按鈕

A、html代碼中加入開始按鈕,并定位他于畫布的中間

<img id="BtnImgStart" style="position: absolute; left: 200px; top: 200px; cursor: pointer; float: left; display: block; " src="./images/START-Button.png">

B、全局變量

var gameRunning = false;//游戲運(yùn)行狀態(tài)      var gameloopId;//記住循環(huán)的變量

C、原來是游戲自己開始沒有暫停的、寫一個(gè)開始暫停的函數(shù)

//開始或者暫停游戲      function ToggleGameplay()      {          gameRunning = !gameRunning;          if(gameRunning)          {              $("#BtnImgStart").hide();               gameloopId = setInterval(GameLoop, 10);           }else          {              clearInterval(gameloopId);          }      }

D、添加開始按鈕事件

//事件處理         function AddEventHandlers()         {             //鼠標(biāo)移動(dòng)則蘑菇跟著移動(dòng)             $("#container").mousemove(function(e){                 mushroom.x = e.pageX - (mushroom.image.width/2);             });           //開始按鈕             $("#BtnImgStart").click(function (){                      ToggleGameplay();          });      }

注意,要把$(window).ready(function(){})函數(shù)中的setInterval(GameLoop, 10);去掉

二、添加生命數(shù)條

A、需要的全局變量

var lives=3;//3條生命數(shù)      var livesImages = new Array();//生命圖片數(shù)組

B、生命圖片初始化

//生命圖片因?yàn)橹挥?個(gè),所以最多只能6個(gè)      for(var x=0; x<6; x++)      {          livesImages[x] = new Image();             livesImages[x].src = "images/lives" + x + ".png";      }

C、繪制生命條

//描繪生命條      function DrawLives()      {          ctx.drawImage(livesImages[lives], 0, 0);      }

D、當(dāng)熊碰到底線時(shí),減一條生命

//熊碰到下面邊界      if(animal.y>screenHeight - animal.image.height)      {          lives -=1;//生命減1         //當(dāng)還有生命條時(shí),暫停游戲,熊回到中間位置,顯出開始按鈕        if(lives>0)          {              horizontalSpeed = speed; //初始化水平速度             verticalSpeed = -speed; //初始化垂直速度            animal.x = parseInt(screenWidth/2); //初始化熊的x坐標(biāo)            animal.y = parseInt(screenHeight/2); //初始化熊的y坐標(biāo)              $("#BtnImgStart").show(); //顯示開始按鈕             ToggleGameplay(); //暫停游戲             GameLoop(); //初始化繪圖         }      }

E、當(dāng)生命條數(shù)等于0或者獎(jiǎng)品消滅完,游戲結(jié)束

//結(jié)束游戲      function GameOver()      {          gameRunning = false;          clearInterval(gameloopId);          alert("游戲結(jié)束!");      }

在熊撞到底線的代碼中,加入判斷,當(dāng)生命數(shù)=0時(shí),游戲結(jié)束

if(lives<=0)          GameOver();

在繪制獎(jiǎng)品函數(shù)中加入判斷,當(dāng)獎(jiǎng)品被消滅完時(shí),游戲結(jié)束

//繪制獎(jiǎng)品,把獎(jiǎng)品顯示在畫布上      function DrawPrizes()      {          for(var x=0; x<prizes.length; x++)          {              currentPrize = prizes[x];                         //假如沒有被撞擊,則描繪              if(!currentPrize.hit)              {                  ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);              }          }          if(AllPrizesHit())          {              GameOver();          }      }      //判斷是否撞完獎(jiǎng)品,假如其中有一個(gè)      function AllPrizesHit()      {          for(var c=0; c<prizes.length; c++)          {              checkPrize = prizes[c];              if(checkPrize.hit == false)                  return false;                            }          return true;      }

三、添加得分

A、定義全局變量

var score = 0;//分?jǐn)?shù)      var scoreImg = new Image();//分?jǐn)?shù)板

B、初始化分?jǐn)?shù)板

scoreImg.src = "images/score.png";//分?jǐn)?shù)板

C、給獎(jiǎng)品加一個(gè)分?jǐn)?shù)屬性。這樣在撞獎(jiǎng)品時(shí)才能知道得到多少分

function Prize() {};      Prize.prototype = new GameObject();//繼承游戲?qū)ο驡ameObject      Prize.prototype.row = 0;//獎(jiǎng)品行位置      Prize.prototype.col = 0;//獎(jiǎng)品列位置      Prize.prototype.hit = false;//是否被撞過      Prize.prototype.point = 0;//分?jǐn)?shù)

D、在初始化獎(jiǎng)品數(shù)組中加入分?jǐn)?shù)

//創(chuàng)建獎(jiǎng)品數(shù)組      function InitPrizes()      {          var count=0;          //一共3行          for(var x=0; x<3; x++)          {              //一共23列              for(var y=0; y<23; y++)              {                  prize = new Prize();                  if(x==0)                  {                      prize.image = flowerImg;//鮮花放在***行                      prize.point = 3;//鮮花3分                  }                  if(x==1)                  {                      prize.image = acornImg;//豫子剛在第2行                      prize.point = 2;//橡子2分                  }                  if(x==2)                  {                      prize.image = leafImg;//葉子放在第3行                      prize.point = 1;//葉子1分                  }                                        prize.row = x;                  prize.col = y;                  prize.x = 20 * prize.col + 10;//x軸位置                  prize.y = 20 * prize.row + 40;//y軸位置                  //裝入獎(jiǎng)品數(shù)組,用來描繪                  prizes[count] = prize;                  count++;              }          }      }

E、當(dāng)熊撞到獎(jiǎng)品時(shí),根據(jù)碰撞獎(jiǎng)品的分?jǐn)?shù)增加總分

//撞到獎(jiǎng)品      function HasAnimalHitPrize()      {          //取出所有獎(jiǎng)品          for(var x=0; x<prizes.length; x++)          {              var prize = prizes[x];              //假如沒有碰撞過              if(!prize.hit)              {                  //判斷碰撞                  if(CheckIntersect(prize, animal, 0))                  {                      prize.hit = true;                      //熊反彈下沉                      verticalSpeed = speed;                      //總分增加                      score += prize.point;                  }              }          }           }

F、繪制分?jǐn)?shù)

//描繪分?jǐn)?shù)      function DrawScore()      {          ctx.drawImage(scoreImg, screenWidth-(scoreImg.width),0);//分?jǐn)?shù)板          ctx.font = "12pt Arial";          ctx.fillText("" + score, 425, 25);  //得分      }

綜合上面的代碼, 到此第八回的完整代碼如下:

<!DOCTYPE>        <html>        <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <title>繪制獎(jiǎng)品-html5中文網(wǎng)</title>        <!-- 要記得引用jquery-1.4.2.js -->     <script type="text/javascript" src="./js/jquery-1.4.2.js"></script>        <script type="text/javascript" >            //全局變量             var backgroundForestImg = new Image();//森林背景圖             var mushroomImg = new Image();//蘑菇           var bearEyesClosedImg = new Image();//閉著眼睛的熊熊           var ctx;//2d畫布             var screenWidth;//畫布寬度             var screenHeight;//畫布高度           var speed = 2;//不變常量,從新開始的速度            var horizontalSpeed = speed;//水平速度,隨著熊的碰撞會(huì)發(fā)生改變          var verticalSpeed = -speed; //垂直速度,開始肯定是要向上飄,所以要負(fù)數(shù),隨著熊的碰撞會(huì)發(fā)生改變          var bearAngle = 2;//熊旋轉(zhuǎn)的速度          var flowerImg = new Image();//獎(jiǎng)品鮮花          var leafImg = new Image();//獎(jiǎng)品葉子          var acornImg = new Image();//獎(jiǎng)品橡子          var gameRunning = false;//游戲運(yùn)行狀態(tài)          var gameloopId;//記住循環(huán)的變量          var lives=3;//3條生命數(shù)          var livesImages = new Array();//生命圖片數(shù)組          var score = 0;//分?jǐn)?shù)          var scoreImg = new Image();//分?jǐn)?shù)板          //公用 定義一個(gè)游戲物體戲?qū)ο?nbsp;            function GameObject()             {                 this.x = 0;                 this.y = 0;                 this.image = null;             }                          //定義蘑菇Mushroom 繼承游戲?qū)ο驡ameObject             function Mushroom() {};             Mushroom.prototype = new GameObject();//游戲?qū)ο驡ameObject             //蘑菇實(shí)例             var mushroom = new Mushroom();        //循環(huán)描繪物體                       //定義動(dòng)物熊 Animal 繼承 游戲?qū)ο驡ameObject          function Animal() {};          Animal.prototype = new GameObject();//游戲?qū)ο驡ameObject          Animal.prototype.angle = 0;//動(dòng)物的角度,目前中(即作為動(dòng)物它在屏幕上旋轉(zhuǎn)退回)          //定義熊實(shí)例           var animal = new Animal();                    //定義獎(jiǎng)品數(shù)組Prizes和對(duì)象Prize,繼承游戲?qū)ο驡ameObject          var prizes = new Array();          function Prize() {};          Prize.prototype = new GameObject();//繼承游戲?qū)ο驡ameObject          Prize.prototype.row = 0;//獎(jiǎng)品行位置          Prize.prototype.col = 0;//獎(jiǎng)品列位置          Prize.prototype.hit = false;//是否被撞過          Prize.prototype.point = 0;//分?jǐn)?shù)                    function GameLoop()             {                 //清除屏幕                 ctx.clearRect(0, 0, screenWidth, screenHeight);                 ctx.save();                 //繪制背景                 ctx.drawImage(backgroundForestImg, 0, 0);                 //繪制蘑菇                 ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);               //繪制獎(jiǎng)品              DrawPrizes();              //繪制生命條              DrawLives();              //繪制分?jǐn)?shù)板              DrawScore();                      //繪制熊              //改變移動(dòng)動(dòng)物X和Y位置              animal.x += horizontalSpeed;              animal.y += verticalSpeed;              //改變翻滾角度              animal.angle += bearAngle;              //以當(dāng)前熊的中心位置為基準(zhǔn)              ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));              //根據(jù)當(dāng)前熊的角度輪換              ctx.rotate(animal.angle * Math.PI/180);              //描繪熊              ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));                   ctx.restore();              //檢測(cè)是否碰到邊界              HasAnimalHitEdge();              //檢測(cè)熊碰撞蘑菇              HasAnimalHitMushroom();              //檢測(cè)熊碰撞獎(jiǎng)品              HasAnimalHitPrize();              }             //加載圖片             function LoadImages()             {                 mushroomImg.src = "images/mushroom.png";//蘑菇                 backgroundForestImg.src = "images/forest1.jpg";//森林背景圖                bearEyesClosedImg.src = "images/bear_eyesclosed.png";//閉著眼睛的              flowerImg.src = "images/flower.png";//獎(jiǎng)品花              acornImg.src = "images/acorn.png";//獎(jiǎng)品橡子              leafImg.src = "images/leaf.png";//獎(jiǎng)品葉子              scoreImg.src = "images/score.png";//分?jǐn)?shù)板              //生命圖片因?yàn)橹挥?個(gè),所以最多只能6個(gè)              for(var x=0; x<6; x++)              {                  livesImages[x] = new Image();                     livesImages[x].src = "images/lives" + x + ".png";              }                            mushroom.image = mushroomImg;                 animal.image = bearEyesClosedImg;              backgroundForestImg.onload = function(){GameLoop(); };          }           //熊碰撞邊界          function HasAnimalHitEdge()          {              //熊碰到右邊邊界              if(animal.x>screenWidth - animal.image.width)              {                  if(horizontalSpeed > 0)//假如向右移動(dòng)                      horizontalSpeed =-horizontalSpeed;//改變水平速度方向              }              //熊碰到左邊邊界              if(animal.x<-10)              {                  if(horizontalSpeed < 0)//假如向左移動(dòng)                      horizontalSpeed = -horizontalSpeed;//改變水平速度方向              }              //熊碰到下面邊界              if(animal.y>screenHeight - animal.image.height)              {                  lives -=1;//生命減1                  if(lives>0)                  {                      horizontalSpeed = speed;                      verticalSpeed = -speed;                      animal.x = parseInt(screenWidth/2);                      animal.y = parseInt(screenHeight/2);                      $("#BtnImgStart").show();                      ToggleGameplay();                      GameLoop();                  }              }              //熊碰到上邊邊界              if(animal.y<0)              {                  verticalSpeed = -verticalSpeed;              }              if(lives<=0)                  GameOver();          }          //事件處理             function AddEventHandlers()             {                 //鼠標(biāo)移動(dòng)則蘑菇跟著移動(dòng)                 $("#container").mousemove(function(e){                     mushroom.x = e.pageX - (mushroom.image.width/2);                 });               //開始按鈕                 $("#BtnImgStart").click(function (){                          ToggleGameplay();              });          }           //檢測(cè)2個(gè)物體是否碰撞          function CheckIntersect(object1, object2, overlap)          {              //    x-軸                      x-軸              //  A1------>B1 C1              A2------>B2 C2              //  +--------+   ^              +--------+   ^              //  | object1|   | y-軸         | object2|   | y-軸              //  |        |   |              |        |   |              //  +--------+  D1              +--------+  D2              //              //overlap是重疊的區(qū)域值              A1 = object1.x + overlap;              B1 = object1.x + object1.image.width - overlap;              C1 = object1.y + overlap;              D1 = object1.y + object1.image.height - overlap;                         A2 = object2.x + overlap;              B2 = object2.x + object2.image.width - overlap;              C2 = object2.y + overlap;              D2 = object2.y + object2.image.width - overlap;                         //假如他們?cè)趚-軸重疊              if(A1 > A2 && A1 < B2                || B1 > A2 && B1 < B2)              {                  //判斷y-軸重疊                  if(C1 > C2 && C1 < D1                || D1 > C2 && D1 < D2)                  {                      //碰撞                      return true;                  }                         }              return false;          }          //動(dòng)物碰撞蘑菇          function HasAnimalHitMushroom()          {              //假如碰撞              if(CheckIntersect(animal, mushroom, 5))              {                  //假如碰撞的位置屬于蘑菇的左下位置                  if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))                  {                      horizontalSpeed = -speed;//反彈                  }                  //假如碰撞的位置屬于蘑菇的左上位置                  else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.5))                  {                      //反彈速度減半                      horizontalSpeed = -speed/2;                  }                  //假如碰撞的位置屬于蘑菇的右上位置                  else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.75))                  {                      horizontalSpeed = speed/2;                  }                  else                  {                      horizontalSpeed = speed;                  }                  verticalSpeed = -speed;//改變垂直速度。也即動(dòng)物向上移動(dòng)                         }          }          //創(chuàng)建獎(jiǎng)品數(shù)組          function InitPrizes()          {              var count=0;              //一共3行              for(var x=0; x<3; x++)              {                  //一共23列                  for(var y=0; y<23; y++)                  {                      prize = new Prize();                      if(x==0)                      {                          prize.image = flowerImg;//鮮花放在***行                          prize.point = 3;//3分                      }                      if(x==1)                      {                          prize.image = acornImg;//豫子剛在第2行                          prize.point = 2;//2分                      }                      if(x==2)                      {                          prize.image = leafImg;//葉子放在第3行                          prize.point = 1;//1分                      }                                                prize.row = x;                      prize.col = y;                      prize.x = 20 * prize.col + 10;//x軸位置                      prize.y = 20 * prize.row + 40;//y軸位置                      //裝入獎(jiǎng)品數(shù)組,用來描繪                      prizes[count] = prize;                      count++;                  }              }          }          //繪制獎(jiǎng)品,把獎(jiǎng)品顯示在畫布上          function DrawPrizes()          {              for(var x=0; x<prizes.length; x++)              {                  currentPrize = prizes[x];                             //假如沒有被撞擊,則描繪                  if(!currentPrize.hit)                  {                      ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);                  }              }              if(AllPrizesHit())              {                  GameOver();              }          }                    //撞到獎(jiǎng)品          function HasAnimalHitPrize()          {              //取出所有獎(jiǎng)品              for(var x=0; x<prizes.length; x++)              {                  var prize = prizes[x];                  //假如沒有碰撞過                  if(!prize.hit)                  {                      //判斷碰撞                      if(CheckIntersect(prize, animal, 0))                      {                          prize.hit = true;                          //熊反彈下沉                          verticalSpeed = speed;                          //總分增加                          score += prize.point;                      }                  }              }               }          //判斷是否撞完獎(jiǎng)品,假如其中有一個(gè)          function AllPrizesHit()          {              for(var c=0; c<prizes.length; c++)              {                  checkPrize = prizes[c];                  if(checkPrize.hit == false)                      return false;                                    }              return true;          }          //開始或者暫停游戲          function ToggleGameplay()          {              gameRunning = !gameRunning;              if(gameRunning)              {                  $("#BtnImgStart").hide();                   gameloopId = setInterval(GameLoop, 10);               }else              {                  clearInterval(gameloopId);              }          }          //結(jié)束游戲          function GameOver()          {              gameRunning = false;              clearInterval(gameloopId);              alert("游戲結(jié)束!");          }          //描繪生命條          function DrawLives()          {              ctx.drawImage(livesImages[lives], 0, 0);          }          //描繪分?jǐn)?shù)          function DrawScore()          {              ctx.drawImage(scoreImg, screenWidth-(scoreImg.width),0);//分?jǐn)?shù)板              ctx.font = "12pt Arial";              ctx.fillText("" + score, 425, 25);  //得分          }          //初始化             $(window).ready(function(){                  AddEventHandlers();//添加事件                LoadImages();                         ctx = document.getElementById('canvas').getContext('2d'); //獲取2d畫布                    screenWidth = parseInt($("#canvas").attr("width")); //畫布寬度               screenHeight = parseInt($("#canvas").attr("height"));                 //初始化蘑菇              mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐標(biāo)                mushroom.y = screenHeight - 40;//蘑菇Y(jié)坐標(biāo)                 //初始化熊              animal.x = parseInt(screenWidth/2);              animal.y = parseInt(screenHeight/2);               //初始化獎(jiǎng)品              InitPrizes();                        });                        </script>        </head>                <body>            <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">                <canvas id="canvas" width="480" height="320" >               瀏覽器不支持html5,<a target="_blank" href="http://www.html5china.com/help/browser.html">請(qǐng)下載</a>支持html5的瀏覽器來觀看               </canvas>            </div>               <img id="BtnImgStart" style="position: absolute; left: 200px; top: 200px; cursor: pointer; float: left; display: block; " src="./images/START-Button.png">              </body>        </html>

感謝各位的閱讀,以上就是“怎么用html5實(shí)現(xiàn)蘑菇與熊游戲”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)怎么用html5實(shí)現(xiàn)蘑菇與熊游戲這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI