原生JS小項目之貪喫蛇小遊戲(附源代碼)

公開課鏈接渡一教育貪喫蛇連接

在這裏插入圖片描述

<body>
    <div class="content">
        <div class="btn startBtn"><button></button></div>
        <div class="btn pauseBtn"><button></button></div>
        <div id="snakeWrap">
        
        </div>
    </div>
.content{
    width: 640px;
    height: 640px;
    margin: 50px auto;
    position: relative;
}
.btn{
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: rgba(0,0,0,0);
    z-index: 1;
}
.btn button{
    background: none;
    border:none;
    background-size: 100% 100%;
    cursor: pointer;
    outline: none;
    position: absolute;
    left: 50%;
    top: 50%;
}
.startBtn button{
    width: 200px;
    height: 100px;
    background-image: url("../開始遊戲.png");
    margin-left: -100px;
    margin-top: -50px;
}
.pauseBtn{
    display: none;
}
.pauseBtn button{
    width: 70px;
    height: 70px;
    background-image: url("../遊戲暫停.png");
    margin-left: -35px;
    margin-top: -35px;
}
#snakeWrap{
    position: relative;
    width: 600px;
    height: 600px;
    background: #225675;
    border:20px solid #7dd9ff;
}
.snakeHead{
    background-image: url("../蛇頭.png");
    background-size: cover;
}
.snakeBody{
   background-color: #9ddbb1;
    border-radius: 50%;
}
.food{
    background: url("../食物.png") no-repeat;
    background-size: 100% 100%;
}
var sw = 20,  // 一個方塊的寬度
    sh = 20,  // 高度
    tr = 30,  // 行數
    td = 30;  // 列數

var snake = null,  // 蛇的實例
    food = null,  // 食物的實例
    game = null;  // 遊戲實例

// 方塊構造函數
function Square(x,y,classname) {
    this.x = x*sw;
    this.y = y*sh;
    this.class = classname;

    this.viewContent = document.createElement('div');
    this.viewContent.className = this.class;
    this.parent = document.getElementById('snakeWrap');

}

Square.prototype.create = function(){  // 創建方塊dom
    this.viewContent.style.position='absolute';
    this.viewContent.style.width = sw+'px';
    this.viewContent.style.height = sh + 'px';
    this.viewContent.style.left = this.x +'px';
    this.viewContent.style.top = this.y + 'px';

    this.parent.appendChild(this.viewContent)

}

Square.prototype.remove = function() {
    this.parent.removeChild(this.viewContent);
}

// 蛇
function Snake () {
    this.head = null; //蛇頭
    this.tail = null; // 蛇尾
    this.pos = []; // 存儲蛇身上的每一個方塊的位置
    this.directionNum = { // 存儲蛇走的方向,用一個對象來表示
        left:{
            x:-1,
            y:0,
            rotate:180 // 蛇頭旋轉角度
        },
        right:{
            x:1,
            y:0,
            rotate:0
        },
        up:{
            x:0,
            y:-1,
            rotate:-90
        },
        down:{
            x:0,
            y:1,
            rotate:90
        }
    }
}

Snake.prototype.init = function() {
    // 創建蛇頭
    var snakeHead = new Square(2,0,'snakeHead');
    snakeHead.create();
    this.head = snakeHead; // 存儲蛇頭信息
    this.pos.push([2,0])  // 存儲蛇頭位置
    // 創建蛇身體
    var snakeBody1 = new Square(1,0,'snakeBody');
    snakeBody1.create();
    this.pos.push([1,0])  // 存儲蛇身1位置

    var snakeBody2 = new Square(0,0,'snakeBody');
    snakeBody2.create();
    this.tail = snakeBody2; // 存儲蛇尾信息
    this.pos.push([0,0])  // 存儲蛇身1位置

    // 形成鏈表關係
    snakeHead.last = null;
    snakeHead.next = snakeBody1;
    
    snakeBody1.last = snakeHead;
    snakeBody1.next = snakeBody2;

    snakeBody2.last = snakeBody1;
    snakeBody2.next = null;

    // 給蛇添加一個屬性,用來表示蛇走的方向
    this.direction = this.directionNum.right; // 默認往右走

}

// 獲取蛇頭的下一個位置對應的元素,要根據元素做不同的事情
Snake.prototype.getNextPos = function() {
    var nextPos = [
        this.head.x/sw+this.direction.x,
        this.head.y/sh+this.direction.y
    ]
    // 下個點是自己,遊戲結束
    var selfCollied = false; //是否撞到了自己
    this.pos.forEach(function(value) {
        if(value[0]==nextPos[0] && value[1]==nextPos[1]){
            selfCollied = true;
        }
    });
    if(selfCollied){
        console.log('撞到了自己');

        this.strategies.die.call(this);
        return;
    }
    // 下個點是圍牆,遊戲結束
    if(nextPos[0]<0 || nextPos[1]<0 || nextPos[0]>td-1 || nextPos[1]>tr-1){
        console.log('撞到了牆');

        this.strategies.die.call(this);
        return;
    }

    // 下個點是食物,喫
    if(food && food.pos[0]==nextPos[0] && food.pos[1]==nextPos[1]){
        // 如果這個條件成立說明現在蛇頭要走的下一個點是食物的那個點;
        console.log('喫到食物了');
        this.strategies.eat.call(this);
        return;
    }


    // 下個點什麼都不是,走
    this.strategies.move.call(this);
    
};

// 處理碰撞後要做的事
Snake.prototype.strategies = {
    move:function(format) {  // 該參數用於決定是否刪除蛇尾
        // 創建新身體,在舊蛇頭的位置
        var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody');
        // 更新鏈表的關係
        newBody.next = this.head.next;
        newBody.next.last = newBody;
        newBody.last = null;

        this.head.remove(); // 把舊蛇頭從原來的位置刪除
        newBody.create();

        // 創建蛇頭:蛇頭下一個點
        var newHead = new Square(this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y,'snakeHead');
   
         // 更新鏈表的關係
         newHead.next = newBody;
         newHead.last = null;
         newBody.last = newHead;

         newHead.viewContent.style.transform = 'rotate('+this.direction.rotate+'deg)';
               
         newHead.create();

         // 更新蛇身上每一個方塊的座標
         this.pos.splice(0,0,[this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y]);
         this.head = newHead;  //更新this.head
   
        if(!format){  // false: 需要刪除(處理喫之外的操作)
            this.tail.remove();
            this.tail = this.tail.last;
            this.pos.pop();

        }
        


    },
    eat:function(){
        this.strategies.move.call(this,true);
        createFood();
        game.score++;
    },
    die:function(){
        game.over();
    }
}

snake = new Snake();
// snake.init();

// 創建食物
function createFood(){
    // 食物的隨機座標
    var x = null;
    var y = null;
    var include = true; // 循環跳出的條件,true表示食物座標在蛇身上,false:表示不在
    while(include){
        x = Math.round(Math.random()*(td-1));
        y = Math.round(Math.random()*(tr-1));
        snake.pos.forEach(function(value){
            if(x!=value[0] && y!=value[1]){
                //  座標不在蛇身上
                include = false;
            }
        })
    }
    // 生成食物
    food = new Square(x,y,'food');
    food.pos = [x,y];  // 存儲食物的座標,用於跟蛇頭下一個走的點作對比

    var foodDom = document.querySelector('.food');
    if(foodDom){
        foodDom.style.left = x*sw +'px';
        foodDom.style.top = y*sh +'px';
    }else{
        food.create();
    }
}

// 創建遊戲邏輯
function Game(){
    this.timer = null;
    this.score = 0;

}
Game.prototype.init = function(){
    snake.init();
    createFood();

    document.onkeydown = function(ev) {
        //  用戶按下左鍵, 蛇不能是正在往右走的
        if(ev.which == 37 &&  snake.direction != snake.directionNum.right){
            snake.direction = snake.directionNum.left;
        }else if(ev.which == 38 &&  snake.direction != snake.directionNum.down){
            snake.direction = snake.directionNum.up;
        }else if(ev.which == 39 &&  snake.direction != snake.directionNum.left){
            snake.direction = snake.directionNum.right;
        }else if(ev.which == 40 &&  snake.direction != snake.directionNum.up){
            snake.direction = snake.directionNum.down;
        }
    }

    this.start();

}

Game.prototype.start = function(){
    // 開始遊戲
    this.timer = setInterval(function(){
        snake.getNextPos();
        
    },200);
}
Game.prototype.pause = function() {
    clearInterval(this.timer);
}
Game.prototype.over = function() {
    clearInterval(this.timer);
    alert('你的得分爲:'+ this.score);

    // 遊戲回到最初始的狀態
    var snakeWrap = document.getElementById('snakeWrap');
    snakeWrap.innerHTML = '';
    snake = new Snake();
    game = new Game();

    var startBtnWrap = document.querySelector('.startBtn');
    startBtnWrap.style.display = 'block';
}


// 開啓遊戲
game = new Game();

var startBtn = document.querySelector('.startBtn button');
startBtn.onclick = function(){
    startBtn.parentNode.style.display = 'none';
    game.init();
}

// 暫停遊戲
var snakeWrap = document.getElementById('snakeWrap');
var pauseBtn = document.querySelector('.pauseBtn button');
snakeWrap.onclick = function() {
    game.pause();
    pauseBtn.parentNode.style.display='block';
}
pauseBtn.onclick = function() {
    game.start();
    pauseBtn.parentNode.style.display='none';
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章