1. 程式人生 > >JS實現最簡單的貪吃蛇小遊戲(面向物件思想)

JS實現最簡單的貪吃蛇小遊戲(面向物件思想)

本次練習主要是練習javaScript的面對物件思想

話不多說,先看看效果圖


功能描述:1.小蛇在指定地圖內移動,撞到邊界即彈窗,顯示遊戲結束

                  2.通過上、下、左、右四個按鍵,控制小蛇運動的方向

                   3.隨機產生“食物”,小蛇吃到食物就變長。地圖再次出現食物

                    4.統計分數,每吃一個食物就加一分

具體封裝如下

1.食物物件(食物的橫縱座標,寬和高,背景顏色)
     *
     * 食物需要畫出來---渲染出來--畫,隨機的畫,在畫食物的時候要先刪除原來的食物
     *
 2 .小蛇物件(寬,高,方向)
     * 蛇需要畫出來---渲染出來--畫,每走一次,需要把前一次的小蛇刪除
     * 蛇走的時候,需要方向,是否吃到了食物
     * 小蛇移動的時候,是否吃了食物(吃了就要把小蛇的後面加一個食物的寬和高,顏色,無非就是把原來的蛇尾複製了一個加入到        body中,------>把蛇尾拿出來再次加入到蛇尾的後面)
     
 3. 遊戲物件(初始化食物,初始化小蛇,自動移動小蛇,判斷按鍵)

     * 自動的設定小蛇移動,判斷小蛇是否撞牆,使用者按下了什麼方向鍵

具體實現程式碼如下:

1.html部分,html部分比較簡單,主要是顯示一個地圖,設定樣式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>貪吃蛇</title>
    <style>
        h1{
            text-align: center;
        }
        .map{
            width: 800px;
            height: 600px;
            /*background-color: #ccc;*/
            background-image:url("bg.jpg");
            position: relative;
            /*子絕父相*/
            margin: 10px auto;
        }
        .score{
            width: 100px;
            height: 50px;
            background-color: #cccfff;
            position: absolute;
            right: -105px;
            font-size: 20px;
            line-height: 50px;
            text-align: center;
        }
    </style>
</head>
<body>
<!--建立地圖,設定地圖樣式-->
<h1>貪吃蛇</h1>
<div class="map">
    <div class="score"id="scroe">0分</div>
</div>
</body>
</html>

2.js部分的程式碼

<script>
    // 自呼叫函式---食物
    (function(){
        //定義一個數組,儲存產生的div
        var element=[];
        //自定義建構函式,建立食物物件
        function Food(width,height,color,x,y,) {
            this.width=width||20;
            this.height=height||20;
            this.color=color||"red";
            this.x=x||0;
            this.y=y||0;
        }
        //初始化食物,因為需要在地圖上生成,故需傳入引數map
        Food.prototype.init=function (map) {
            remove();
            var div=document.createElement("div");
            map.appendChild(div);
            div.style.width=this.width+"px";
            div.style.height=this.height+"px";
            div.style.backgroundColor=this.color;
            div.style.position="absolute";
            //產生隨機座標
            this.x=parseInt(Math.random()*(map.offsetWidth/this.width))*this.width;
            this.y=parseInt(Math.random()*(map.offsetHeight/this.height))*this.height;
            div.style.left=this.x+"px";
            div.style.top=this.y+"px";
            element.push(div);
        };
        //刪除食物函式
        function remove(){
            for(var i=0;i<element.length;i++){
                var ele=element[i];
                ele.parentNode.removeChild(ele);//通過食物找到其父元素,再將食物刪除
                //在陣列中將其刪除
                element.splice(i,1);
            }
        }
        //將Food暴露給window
        window.Food=Food;
    }());

    //自呼叫函式---小蛇
    (function(){
        //建構函式,建立小蛇
        var scroe=0;  //統計分數
        var element=[];//建立陣列,存放小蛇
        function Snake(width,height,direction) {
            //小蛇每部分的寬
            this.width=width||20;
            this.height=height||20;
            this.direction=direction||"right";
            this.body=[
                {x:3,y:2,color:"yellow"},//頭
                {x:2,y:2,color:"green"},
                {x:1,y:2,color:"green"}//尾部
            ]
        }
        //小蛇的初始化
        Snake.prototype.init=function (map) {
            remove();
            for(var i=0;i<this.body.length;i++){
                var obj=this.body[i];
                var div=document.createElement("div");
                map.appendChild(div);
                div.style.width=this.width+"px";
                div.style.height=this.height+"px";
                div.style.backgroundColor=obj.color;
                div.style.position="absolute";
                div.style.left=obj.x*this.width+"px";
                div.style.top=obj.y*this.height+"px";
                element.push(div);
            }
        };
        //為原型新增函式---讓小蛇動起來
        Snake.prototype.move=function(food,map){
            var i=this.body.length-1;  //讓蛇的身體動起來
            for(;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 "right":this.body[0].x+=1;break;
                case "left":this.body[0].x-=1;break;
                case "top":this.body[0].y-=1;break;
                case "bottom":this.body[0].y+=1;break;
            }
            //判斷小蛇是否碰到食物
            var headX=this.body[0].x*this.width;
            var headY=this.body[0].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
                    });
                scroe++;
                document.getElementById("scroe").innerText=scroe+"分";
                console.log(scroe);
                food.init(map);//刪掉現有的食物,重新產生食物
            }
        };

        //s刪除小蛇函式
        function remove(){
            var i=element.length-1;
            for(;i>=0;i--){
                var ele=element[i];
                ele.parentNode.removeChild(ele);
                element.splice(i,1);
            }
        }
        window.Snake=Snake;
    }());
    // //自呼叫函式--計分器
    // (function(){
    //
    // }())
    //自呼叫函式---遊戲
    (function () {
        function Game(map){
            this.food=new Food();
            this.snake=new Snake();
            this.map=map;
            that=this;
        }
        //初始化遊戲,顯示小蛇和食物
        Game.prototype.init=function () {
            this.food.init(this.map);
            this.snake.init(this.map);
            this.runSnake(this.food,this.map);
            this.bindkey();
        };

        //讓蛇跑起來
        Game.prototype.runSnake=function(food,map){
            var timeId=setInterval(function () {
                this.snake.move(food,map);
                this.snake.init(map);//這兩次呼叫,就能讓蛇跑起來了

                //下面判斷蛇是否碰到牆
                var MaxX=this.map.offsetWidth/this.snake.width;
                var MaxY=this.map.offsetHeight/this.snake.height;

                var headX=this.snake.body[0].x;
                var headY=this.snake.body[0].y;

                if (headY<0||headY>=MaxY){
                    clearInterval(timeId);
                   alert("遊戲結束");
                }
                if(headX<0||headX>=MaxX){
                    clearInterval(timeId);
                    alert("遊戲結束");
                }
            }.bind(that),150);
        };

        //新增原型物件---改變蛇運動的方向
        Game.prototype.bindkey=function(){
          document.addEventListener("keydown",function (e) {
              switch (e.keyCode){
                  case 37:this.snake.direction="left";break;
                  case 38:this.snake.direction="top";break;
                  case 39:this.snake.direction="right";break;
                  case 40:this.snake.direction="bottom";break;
              }
          }.bind(that),false);
        };
        window.Game=Game;
    }());
    //測試
    var game=new Game(document.querySelector(".map"));
    game.init();

</script>

背景圖:bg.jpg