用js寫一個簡單的貪吃蛇小游戲


一個用原生js寫的貪吃蛇小游戲,貪吃蛇碰到自己身體游戲會結束

效果圖:

 

 

代碼如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<button>按鈕</button>
</body>
<script type="text/javascript">
var timerId;
document.querySelector("button").onclick = function(){
// 讓蛇動起來 - 定時器移動
    timerId = setInterval(()=>{
        s.move()
    },100)
}
// 地圖對象
function Map(){
    // 地圖對象負責創建范圍,放蛇和食物
    this.map = document.createElement("div");
    setStyle(this.map,{
        width:"800px",
        height:"500px",
        background:"pink",
        border:"2px solid #000",
        position:"relative"
    })
    // 將地圖放在body中
    document.body.appendChild(this.map)
}
var m = new Map()
// 食物對象
function Food(){
    // 食物對象負責生成,消失(地圖干掉他)
    this.food = document.createElement("div");
    setStyle(this.food,{
        width:"10px",
        height:"10px",
        background:"blue",
        position:"absolute",
        left:parseInt(getRandom(0,m.map.clientWidth-10)/10)*10+"px",
        top:parseInt(getRandom(0,m.map.clientHeight-10)/10)*10+"px",
    })
    // 將食物放到地圖中
    m.map.appendChild(this.food)
}
var f = new Food()
// 蛇對象
function Snake(){
    // 定義蛇的身體的left和top
    this.body = [
        {
            x:0,
            y:0
        },
        {
            x:10,
            y:0
        },
        {
            x:20,
            y:0
        }
    ]
    // 定義蛇的移動方向
    this.direction = 'right';
    // 通過按鍵改變蛇的移動方向
    this.changeDirection();
    // 顯示蛇的身體
    this.show()
    
}
Snake.prototype.changeDirection = function(){
    document.onkeypress = e=>{
        var e = e || window.event;
        // 獲取鍵碼
        var code = e.keyCode || e.which;
        // 根據鍵碼改變direction屬性
        // console.log(code); // 119 115 97 100
        switch(code){
            case 119:
                this.direction = "up";
            break;
            case 115:
                this.direction = "down";
            break;
            case 97:
                this.direction = "left";
            break;
            case 100:
                this.direction = "right";
            break;
        }
    }
}
Snake.prototype.move = function(){
    console.log(this.direction);
    // 蛇移動需要一個方向 - 默認方向
    // 蛇在移動過程中,不管是哪個方向,移動一步,蛇的第二節身體就是蛇頭原來的位置,蛇的最后一節身體就是,第二節身體原來的位置
    for(var i=0;i<this.body.length-1;i++){
        this.body[i].x = this.body[i+1].x
        this.body[i].y = this.body[i+1].y
    }
    // console.log(this.body);
    // 單獨設置蛇頭
    switch(this.direction){
        case 'up':
            this.body[this.body.length-1].y -= 10;
        break;
        case 'down':
            this.body[this.body.length-1].y += 10;
        break;
        case 'left':
            this.body[this.body.length-1].x -= 10;
        break;
        case 'right':
            this.body[this.body.length-1].x += 10;
        break;
    }
    // console.log(this.body);
    // 根據新的數組顯示身體
    this.show()
    this.eat()
    // 蛇不能撞牆
    this.die()
}
Snake.prototype.die = function(){
    // 撞牆
    if(this.body[this.body.length-1].x>m.map.clientWidth || this.body[this.body.length-1].x<0 || this.body[this.body.length-1].y<0 || this.body[this.body.length-1].y>m.map.clientHeight){
        clearInterval(timerId)
        alert("GAME OVER");
    }
    // 撞身體
    for(var i=0;i<this.body.length-1;i++){
        if(this.body[i].x === this.body[this.body.length-1].x && this.body[i].y === this.body[this.body.length-1].y){
            clearInterval(timerId)
            alert("GAME OVER");
        }
    }
}
Snake.prototype.eat = function(){
    // 蛇頭的x和y跟食物的left和top完全相等的時候就吃到了
    if(this.body[this.body.length-1].x === f.food.offsetLeft && this.body[this.body.length-1].y === f.food.offsetTop){
        // 吃到了
        // 蛇的身體要加一節
        var oneBody = {
            x:this.body[0].x,
            y:this.body[0].y
        }
        // 將這個對象放到身體數組的最前面
        this.body.unshift(oneBody)
        // 根據新的數組生成新的身體
        this.show()
        // 食物要消失,並再生成一個
        f.food.parentElement.removeChild(f.food)
        f = new Food()
    }
}
Snake.prototype.show = function(){
    // 先刪除之前的身體 - 再創建新的身體
    var snakes = m.map.querySelectorAll(".snake")
    // console.log(snakes);
    if(snakes.length !== 0){
        for(var i=0;i<snakes.length;i++){
            snakes[i].parentElement.removeChild(snakes[i])
        }
    }
    // 遍歷身體屬性,創建div
    for(var i=0;i<this.body.length;i++){
        var div = document.createElement("div");
        div.className = 'snake';
        setStyle(div,{
            width:"10px",
            height:"10px",
            background:"#0f0",
            position:"absolute",
            left:this.body[i].x + "px",
            top:this.body[i].y + "px"
        });
        if(i === this.body.length-1){
            div.style.background = 'red';
        }
        m.map.appendChild(div);
    }
}
var s = new Snake()

function setStyle(ele,styleObj){
    for(var attr in styleObj){
        ele.style[attr] = styleObj[attr];
    }
}
function getRandom(min,max){
    if(min>max){
        var tmp = min;
        min = max;
        max = tmp;
    }
    return parseInt(Math.random()*(max-min)+1);
}
</script>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM