国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JS實現的貪吃蛇游戲完整實例

2019-11-19 12:16:14
字體:
來源:轉載
供稿:網友

本文實例講述了JS實現的貪吃蛇游戲。分享給大家供大家參考,具體如下:

思想:

1、設計蛇:屬性有寬、高、方向、狀態(有多少節),方法:顯示,跑

2、設計食物:屬性寬、高

3、顯示蛇:根據狀態向地圖里加元素

4、蛇跑起來:下一節到前一節的位置,蛇頭根據方向變,刪除原來的蛇,新建蛇;當出界時,死亡,初始化;當蛇頭吃到自己的時候,死亡,初始化

5、食物被吃掉,蛇加一節,去掉原來的食物,生成新的食物

6、添加定時器,綁定按鍵

完整示例:

<!doctype html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"     content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>Document</title>  <style type="text/css">    body {      margin: 0;      padding: 0;    }    .main {      width: 800px;      height: 400px;      margin: 50px auto;    }    .btn {      width: 100px;      height: 40px;    }    .map {      position: relative;      width: 800px;      height: 400px;      background: #ccc;    }  </style></head><body><div class="main">  <button class="btn" id="begin">開始游戲</button>  <div class="map" id="map"></div>  <script type="text/javascript">    var map = document.getElementById('map');    // 使用構造方法創建蛇,    function Snake()    {      // 設置蛇的寬、高、默認走的方向      this.width = 10;      this.height = 10;      this.direction = 'right';      // 記住蛇的狀態,當吃完食物的時候,就要加一個,初始為3個小點為一個蛇,      this.body = [        {x:2, y:0},  // 蛇頭,第一個點        {x:1, y:0},  // 蛇脖子,第二個點        {x:0, y:0}  // 蛇尾,第三個點      ];      // 顯示蛇      this.display = function() {        // 創建蛇        for (var i=0; i<this.body.length; i++) {          if (this.body[i].x != null) {  // 當吃到食物時,x==null,不能新建,不然會在0,0處新建一個            var s = document.createElement('div');            // 將節點保存到狀態中,以便于后面刪除            this.body[i].flag = s;            // 設置寬高            s.style.width = this.width + 'px';            s.style.height = this.height + 'px';            s.style.borderRadius = "50%";            s.style.background = "rgb(" + Math.floor(Math.random()*256) + "," + Math.floor(Math.random()*256) + "," + Math.floor(Math.random()*256) + ")";            // 設置位置            s.style.position = 'absolute';            s.style.left = this.body[i].x * this.width + 'px';            s.style.top = this.body[i].y * this.height + 'px';            // 添加進去            map.appendChild(s);          }        }      };      // 讓蛇跑起來,后一個元素到前一個元素的位置      // 蛇頭根據方向處理,所以i不能等于0      this.run = function() {        // 后一個元素到前一個元素的位置        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;        }        // 根據方向處理蛇頭        switch(this.direction)        {          case "left":            this.body[0].x -= 1;            break;          case "right":            this.body[0].x += 1;            break;          case "up":            this.body[0].y -= 1;            break;          case "down":            this.body[0].y += 1;            break;        }        // 判斷是否出界,一蛇頭判斷,出界的話,        if (this.body[0].x < 0 || this.body[0].x > 79 || this.body[0].y < 0 || this.body[0].y > 39) {          clearInterval(timer);  // 清除定時器,          alert("你瞎嗎?撞死了!");          // 刪除舊的          for (var i=0; i<this.body.length; i++) {            if (this.body[i].flag != null) {  // 如果剛吃完就死掉,會加一個值為null的              map.removeChild(this.body[i].flag);            }          }          this.body = [  // 回到初始狀態,            {x:2, y:0},            {x:1, y:0},            {x:0, y:0}          ];          this.direction = 'right';          this.display();  // 顯示初始狀態          return false;  // 結束        }        // 判斷蛇頭吃到食物,xy坐標重合,        if (this.body[0].x == food.x && this.body[0].y == food.y) {          // 蛇加一節,因為根據最后節點定,下面display時,會自動賦值的          this.body.push({x:null, y:null, flag: null});          // 清除食物,重新生成食物          map.removeChild(food.flag);          food.display();        }        // 吃到自己死亡,從第五個開始與頭判斷,因為前四個永遠撞不到        for (var i=4; i<this.body.length; i++) {          if (this.body[0].x == this.body[i].x && this.body[0].y == this.body[i].y) {            clearInterval(timer);  // 清除定時器,            alert("傻子!你怎么能吃自己呢?");            // 刪除舊的            for (var i=0; i<this.body.length; i++) {              if (this.body[i].flag != null) {  // 如果剛吃完就死掉,會加一個值為null的                map.removeChild(this.body[i].flag);              }            }            this.body = [  // 回到初始狀態,              {x:2, y:0},              {x:1, y:0},              {x:0, y:0}            ];            this.direction = 'right';            this.display();  // 顯示初始狀態            return false;  // 結束          }        }        // 先刪掉初始的蛇,在顯示新蛇        for (var i=0; i<this.body.length; i++) {          if (this.body[i].flag != null) {  // 當吃到食物時,flag是等于null,且不能刪除            map.removeChild(this.body[i].flag);          }        }        // 重新顯示蛇        this.display();      }    }    // 構造食物    function Food()    {      this.width = 10;      this.height = 10;      this.display = function() {        var f = document.createElement('div');        this.flag = f;        f.style.width = this.width + 'px';        f.style.height = this.height + 'px';        f.style.background = 'red';        f.style.borderRadius = '50%';        f.style.position = 'absolute';        this.x = Math.floor(Math.random()*80);        this.y = Math.floor(Math.random()*40);        f.style.left = this.x * this.width + 'px';        f.style.top = this.y * this.height + 'px';        map.appendChild(f);      }    }    var snake = new Snake();    var food = new Food();    snake.display();  // 初始化顯示    food.display();    // 給body加按鍵事件,上下左右    document.body.onkeydown = function(e) {      // 有事件對象就用事件對象,沒有就自己創建一個,兼容低版本瀏覽器      var ev = e || window.event;      switch(ev.keyCode)      {        case 38:          if (snake.direction != 'down') {  // 不允許返回,向上的時候不能向下            snake.direction = "up";          }          break;        case 40:          if (snake.direction != "up") {            snake.direction = "down";          }          break;        case 37:          if (snake.direction != "right") {            snake.direction = "left";          }          break;        case 39:          if (snake.direction != "left") {            snake.direction = "right";          }          break;      }    };    // 點擊開始時,動起來    var begin = document.getElementById('begin');    var timer;    begin.onclick = function() {      clearInterval(timer);      // timer = setInterval(snake.run(), 500);  // 先執行run函數,把執行得到的結果,每500毫秒執行一次,不會在執行內部代碼      timer = setInterval("snake.run()", 500); // 小技巧,每500毫秒執行字符串,字符串執行內部代碼    };  </script></div></body></html>

使用在線HTML/CSS/JavaScript代碼運行工具http://tools.VeVB.COm/code/HtmlJsRun測試上述代碼,可得到如下運行效果:

更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數學運算用法總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript數組操作技巧總結》、《JavaScript排序算法總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》及《JavaScript錯誤與調試技巧總結

希望本文所述對大家JavaScript程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 内乡县| 朝阳市| 长治县| 界首市| 岱山县| 海阳市| 辛集市| 临汾市| 黎城县| 开化县| 贵溪市| 连平县| 盐池县| 乌拉特中旗| 海阳市| 县级市| 玛纳斯县| 安达市| 兴业县| 富民县| 永寿县| 安龙县| 新建县| 天镇县| 安仁县| 容城县| 黄浦区| 青铜峡市| 长丰县| 新密市| 南岸区| 隆安县| 丁青县| 宾阳县| 仙居县| 乡城县| 通化市| 萨迦县| 邢台县| 林口县| 逊克县|