溫馨提示×

溫馨提示×

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

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

JavaScript面向?qū)ο缶幊绦∮螒蛑澇陨叩氖纠治?/h1>
發(fā)布時間:2021-06-18 14:07:35 來源:億速云 閱讀:124 作者:小新 欄目:web開發(fā)

這篇文章主要為大家展示了“JavaScript面向?qū)ο缶幊绦∮螒蛑澇陨叩氖纠治觥?,?nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“JavaScript面向?qū)ο缶幊绦∮螒蛑澇陨叩氖纠治觥边@篇文章吧。

1 面向?qū)ο缶幊趟枷朐诔绦蝽椖恐杏兄浅C黠@的優(yōu)勢:
1- 1 代碼可讀性高.由于繼承的存在,即使改變需求,那么維護(hù)也只是在局部模塊
1-2 維護(hù)非常方便并且成本較低。

2 這個demo是采用了面向?qū)ο蟮木幊趟枷? 用JavaScript 語言編寫的游戲小程序--貪吃蛇.
代碼注釋詳細(xì),邏輯清晰 . 非常適合新手前端開發(fā)者, 鍛煉JavaScript語言的面向?qū)ο蟮木幊趟枷? 
該小Demo已上傳GitHub,歡迎下載!  覺得好的話,隨手給個star,  您的star是我最大的動力!

https://github.com/XingJYGo/snakePlay#javascript-經(jīng)典面向?qū)ο骴emo-貪吃蛇

代碼展示:
代碼結(jié)構(gòu):
--index.html 地圖頁面,展示蛇和食物,進(jìn)行游戲
--food.js   構(gòu)造食物對象
--game.js   構(gòu)造游戲?qū)ο?br/>--snake.js   構(gòu)造蛇對象
--tool.js   常用數(shù)據(jù)工具封裝

--index.html 地圖頁面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>
  #map{
   width: 500px;
   height: 500px;
   background-color: lightblue;
   position: relative;
  }
  
 </style>
</head>
<body>
<div id="map">
 
</div>
<button id="btn">模擬蛇吃到食物</button>
<script src="tool.js"></script>
<script src="food.js"></script>
<script src="snake.js"></script>
<script src="game.js"></script>
<script>
 
////==========前后方向設(shè)定后 ==================
var game = new Game();
game.start();
 
 
 
</script>
 
</body>
</html>

--food.js   構(gòu)造食物對象

// 封裝一個食物對象
//沙箱模式
(function(){
 var container; //用于存儲之前的食物
 function Food(option) {
  //防止用戶不傳參數(shù)會報錯
  option = option || {};
  this.width = option.width || 20;
  this.height = option.height || 20;
  this.bgc = option.bgc || 'orange';
  this.x = option.x || 0;
  this.y = option.y || 0;
  this.borderRadius = option.borderRadius |10;
 }
 
 Food.prototype.render = function () {
  //每一次渲染新的之前就把原來的移除掉
  if(container){
   map.removeChild(container);
  }
  // 創(chuàng)建食物對象
  var food = document.createElement('div');
  //存到全局變量里
  container = food;
  food.style.width = this.width + 'px';
  food.style.height = this.height + 'px';
  food.style.backgroundColor = this.bgc;
  food.style.position = 'absolute';
   //獲得隨機(jī)位置
   //由于要讓食物的位置在每一個格子里面,所有獲取隨機(jī)數(shù)的算法要重新計算
  this.x = Tool.getRandom(0, (map.offsetWidth/ this.width-1)) * this.width;
  this.y = Tool.getRandom(0, (map.offsetHeight/ this.height-1)) * this.height;
  food.style.left = this.x + 'px';
  food.style.top = this.y + 'px';
  food.style.borderRadius = this.borderRadius + 'px';
  //渲染上食物
  map.appendChild(food);
 }
 
 //因為要在全局使用Food,需要把Food拿到全局中
 window.Food = Food;
})();

--game.js   構(gòu)造游戲?qū)ο?/p>

(function () {
//  1 由于游戲?qū)ο笠刂粕吆褪澄?
//   所以游戲?qū)ο髴?yīng)該擁有蛇的實(shí)例和食物的實(shí)例
  //存儲定時器的id
  var timeid;
  function Game() {
    this.snake = new Snake();
    this.food = new Food();
  }
 
  //2 開始游戲
  Game.prototype.start = function () {
    this.snake.render();
    this.food.render();
 
    // 2-1 游戲一開始,蛇和食物就渲染出來
    timeid = setInterval(function () {
      //2-2 -1 蛇的數(shù)據(jù)改變
      this.snake.move();
      // 2-3 判斷蛇是否到達(dá)邊界
      var snakeHead = this.snake.body[0];
      //2-3-1 求蛇頭可以移動的水平/垂直坐標(biāo)的最大位置
      var maxX = map.offsetWidth/this.snake.width -1;
      var maxY = map.offsetHeight/this.snake.height -1;
      if (snakeHead.x <0 ||snakeHead.x > maxX ||snakeHead.y <0 ||snakeHead.y > maxY){
        clearInterval(timeid);
        alert("gave over");
        //注:當(dāng)X超出范圍,代碼應(yīng)立即終止,
        // 防止2-2-2 渲染出下一個盒子.展示出來
        return;
      }
 
 
      //2-4 蛇吃食物
      //依據(jù): 蛇頭的坐標(biāo) 和 食物的坐標(biāo)重合
      var snakeX = snakeHead.x * this.snake.width;
      var snakeY = snakeHead.y * this.snake.height;
      var foodX = this.food.x;
      var foodY = this.food.y;
 
      //如果符合條件, 證明吃到了食物
       if (snakeX === foodX && snakeY === foodY){
         // 2-4-1 食物消失, 渲染新食物
         this.food.render();
         // 2-4-2 蛇,變長
         //  其實(shí)就是往snake.body.push個新對象
         //  bug: 為了解決新添加蛇節(jié)閃下的問題, 把蛇的最后一節(jié)對象,作為新的對象.
         var last = this.snake.body[this.snake.body.length -1];
         this.snake.body.push({
           x:last.x,
           y:last.y,
           col:last.col
         })
         // this.snake.body.push(last);
         // 注:last本身已經(jīng)在數(shù)組中了,
       }
      //2-2 -2渲染到頁面上,真正看到的蛇動起來
      this.snake.render();
 
    }.bind(this), 150)
 
    // 3 給頁面注冊鍵盤按下的事件
    // 3-1 監(jiān)聽用戶是否按下了上,下,左,右的按鍵
 
    document.onkeydown = function(e){
      // console.log(this);
      e = e || window.event;
      console.log(e.keyCode);
      // 左37 上38 右39  下40
      switch(e.keyCode){
 
        case 37:
          //3-11 需要找到蛇,修改蛇的direction屬性
          //防止原地掉頭
          if(this.snake.direction === 'right'){
            return;
          }
          this.snake.direction = 'left';
          break;
        case 38:
          if(this.snake.direction === 'bottom'){
            return;
          }
          this.snake.direction = 'top';
          break;
        case 39:
          if(this.snake.direction === 'left'){
            return;
          }
          this.snake.direction = 'right';
          break;
        case 40:
          if(this.snake.direction === 'top') return; //如果if中只有一行代碼就可以不寫花括號,然后這一行代碼要緊跟在if后面記得加分號
          this.snake.direction = 'bottom';
          break;
 
      }
    }.bind(this);
 
 
 
  };
 
  //2-2 蛇變量賦予全局
  window.Game = Game;
 
})();

--snake.js   構(gòu)造蛇對象

(function () {
  var arr = []; //用于存儲蛇的每一節(jié)數(shù)據(jù)
 
  // 1 創(chuàng)建蛇對象
  function Snake(option) {
    option = option || {};
    this.width = option.width || 20;
    this.height = option.height || 20;
    this.body = [
      {x: 3, y: 2, col: 'green'},//蛇頭的位置和顏色
      {x: 2, y: 2, col: 'orange'},//蛇頭身體的位置和顏色
      {x: 1, y: 2, col: 'orange'}];
    this.direction = option.direction || 'right';
  }
 
 
  //2 渲染蛇的方法
  Snake.prototype.render = function () {
    // 2-3 為了防止多個sanke渲染到頁面上,一渲染之前先清除掉原來的
    for (var i = 0; i < arr.length; i++) {
      map.removeChild(arr[i]);//移除頁面上的蛇節(jié)
    }
    arr.splice(0,arr.length);//蛇節(jié)都被移除掉了,那么數(shù)組中也應(yīng)該都移除.
 
    //2-1 根據(jù)body中的個數(shù),動態(tài)的創(chuàng)建蛇節(jié)
    this.body.forEach(function (item, index) {
      //2-0 動態(tài)的創(chuàng)建蛇節(jié)
      var snakeNode = document.createElement('div');
      //2-4 遍歷添加蛇節(jié)新數(shù)據(jù)
      arr.push(snakeNode);
      snakeNode.style.width = this.width + 'px';
      snakeNode.style.height = this.height + 'px';
      snakeNode.style.position = 'absolute';
      snakeNode.style.left = item.x * this.width + 'px';
      snakeNode.style.top = item.y * this.height + 'px';
      snakeNode.style.backgroundColor = item.col;
      map.appendChild(snakeNode);
 
    }.bind(this))
    //  2-2 上面的this是在snake里面,指向snake.`
    //  否則,默認(rèn)指向window
  };
 
 
 
  //3 蛇移動的方法:body 頭數(shù)組賦值給身體.
  Snake.prototype.move = function () {
    //3-1 蛇后面的數(shù)據(jù)給前面
    for (var i = this.body.length -1; i >0; i--) {
      this.body[i].x = this.body[i - 1].x;
      this.body[i].y = this.body[i - 1].y;
    }
  //  3-2暫時蛇頭往右走
  //   this.body[0].x +=1;
  //
  //3-2蛇頭一定的位置,要根據(jù)蛇的方向來決定
    switch(this.direction){
 
      case 'left':
        this.body[0].x -= 1;
        break;
      case 'right':
        this.body[0].x += 1;
        break;
      case 'top':
        this.body[0].y -= 1;
        break;
      case 'bottom':
        this.body[0].y += 1;
        break;
    }
  };
 
 
 
  //賦予全局變量
  window.Snake = Snake;
})();

--tool.js   常用數(shù)據(jù)工具封裝

//用于存放一些常用的功能性的函數(shù)
 
//  function getRandom(){
//
// }
var Tool = {
 //獲取min - max之間的隨機(jī)整數(shù)
 getRandom: function(min, max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
 }
}
 
// Tool.getRandom()

以上是“JavaScript面向?qū)ο缶幊绦∮螒蛑澇陨叩氖纠治觥边@篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

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

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

AI