js-實現貪喫蛇項目

近來在學習JS進階,便學習着做個網頁版貪喫蛇項目。

  • index.html

<!DOCTYPEtml

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="map"></div>
<script src="js/tools.js"></script>
<script src="js/food.js"></script>
<script src="js/snake.js"></script>
<script src="js/game.js"></script>
</body>
</html>

 

  • style.css
#map{
    width: 800px;
    height: 600px;
    background-color: lightgray;
    position: relative;
}

 

  • 該項目需要隨機生成食物的位置,故先準備好相關函數

 tools.js

(function () {
  

  var Tools = {
        getRandom:function (min,max) {
            return Math.floor(Math.random()*(max - min + 1)) + min;
        }
    }
    window.Tools = Tools;
})()

 

  • 對食物的相關操作

food.js

(function () {
    var that;
    function Game(map) {
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        that = this;
    }
    Game.prototype.start = function () {
        //渲染蛇和食物
        this.food.render(map);
        this.snake.render(map);
        //開始遊戲
        //蛇移動
        runSnake();
        //鍵盤控制蛇移動
        bindKey();
        //蛇喫到食物,在移動的時候喫到食物,所以在移動方法中寫

    }
    function runSnake() {
        var timerId = setInterval(function () {
            //定時器的this指的是window,所以需要藉助一個that
            that.snake.move(that.food,that.map);
            that.snake.render(that.map);

            var headX = that.snake.body[0].x;
            var headY = that.snake.body[0].y;
            var maxX = that.map.offsetWidth / that.snake.width;
            var maxY = that.map.offsetHeight / that.snake.height;

            if(headX < 0 || headX >= maxX) {
                alert('Game Over');
                clearInterval(timerId);
            }
            if(headY < 0 || headY >= maxY) {
                alert('Game Over');
                clearInterval(timerId);
            }
        },150)
    }
    function bindKey(){
        document.addEventListener('keydown',function (e) {
            switch (e.keyCode) {
                case 37:
                    that.snake.direction = 'left';
                    break;
                case 38:
                    that.snake.direction = 'bottom';
                    break;
                case 39:
                    that.snake.direction = 'right';
                    break;
                case 40:
                    that.snake.direction = 'top';
                    break;
            }
        })
    }

    window.Game = Game;
}) ()


/*
var map = document.getElementById('map');
var game = new Game(map);
game.start();*/

  • 對蛇的相關操作

snake.js

(function () {
    var position = 'absolute';
    var element = [];

   function Snake(e) {
       e = e || {};

       this.width = e.width || 20;
       this.height = e.height || 20;
       this.direction = e.direction || 'right';
       //蛇身
       this.body = [
           {x: 3, y: 2, color: 'red'},
           {x: 2, y: 2, color: 'blue'},
           {x: 1, y: 2, color: 'blue'}
       ];
   }
   Snake.prototype.render = function (map) {
       for(var i = 0, len = this.body.length; i < len; i ++) {
           var o = this.body[i];
           var div = document.createElement('div');
           map.appendChild(div);
           element.push(div);

           div.style.position = position;
           div.style.width = this.width + 'px';
           div.style.height = this.height + 'px';
           div.style.left = o.x * this.width + 'px';
           div.style.top = o.y * this.height + 'px';
           div.style.backgroundColor = o.color;
       }
   }
   Snake.prototype.move = function(food,map) {
       //刪掉前一次的蛇
       remove();

       //蛇身的移動位置
       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;
       }
       //蛇頭的移動方向
       var head = this.body[0];
       switch (this.direction) {
           case 'right':
               head.x += 1;
               break;
           case 'left':
               head.x -= 1;
               break;
           case 'top':
               head.y += 1;
               break;
           case 'bottom':
               head.y -= 1;
               break;
       }
       //判斷是否喫到食物(食物座標與蛇頭座標是否相同)
       var headX = head.x * this.width;
       var headY = head.y * this.height;
       if (headX === food.x && headY === food.y) {

           //蛇增加一節
           var last = this.body[this.body.length - 1];
           this.body.push({
               x:last.x,
               y:last.y,
               color:last.color
           })

           //食物消失再隨機生成
           food.render(map);
       }
   }
   function remove() {
       for(var i = element.length - 1; i >= 0; i--){
           //刪除div
           element[i].parentNode.removeChild(element[i]);
           //刪除數組中的元素
           element.splice(i,1);
       }
   }

   window.Snake = Snake;
})()
 //調用
/*var map = document.getElementById('map');
var snake = new Snake();
snake.render(map);*/
/*
snake.move();
snake.render(map);
snake.move();
snake.render(map);
snake.move();
snake.render(map);
snake.move();
snake.render(map);*/

 

  • 遊戲操作角度,實現對食物和蛇的同時操作

game.js(

function () {
    var that;
    function Game(map) {
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        that = this;
    }
    Game.prototype.start = function () {
        //渲染蛇和食物
        this.food.render(map);
        this.snake.render(map);
        //開始遊戲
        //蛇移動
        runSnake();
        //鍵盤控制蛇移動
        bindKey();
        //蛇喫到食物,在移動的時候喫到食物,所以在移動方法中寫

    }
    function runSnake() {
        var timerId = setInterval(function () {
            //定時器的this指的是window,所以需要藉助一個that
            that.snake.move(that.food,that.map);
            that.snake.render(that.map);

            var headX = that.snake.body[0].x;
            var headY = that.snake.body[0].y;
            var maxX = that.map.offsetWidth / that.snake.width;
            var maxY = that.map.offsetHeight / that.snake.height;

            if(headX < 0 || headX >= maxX) {
                alert('Game Over');
                clearInterval(timerId);
            }
            if(headY < 0 || headY >= maxY) {
                alert('Game Over');
                clearInterval(timerId);
            }
        },150)
    }
    function bindKey(){
        document.addEventListener('keydown',function (e) {
            switch (e.keyCode) {
                case 37:
                    that.snake.direction = 'left';
                    break;
                case 38:
                    that.snake.direction = 'bottom';
                    break;
                case 39:
                    that.snake.direction = 'right';
                    break;
                case 40:
                    that.snake.direction = 'top';
                    break;
            }
        })
    }

    window.Game = Game;
}) ()


/*
var map = document.getElementById('map');
var game = new Game(map);
game.start();*/

  • 實現整體操作

main.js

(function () {
    var map = document.getElementById('map');
    var game = new Game(map);
    game.start();
})()

代碼已經整理完,後期還可以繼續壓縮完善。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章