簡易貪吃蛇(未考慮布局)原生js

用原生js寫了個貪吃蛇
立個flag 看看A*尋路 以后再改改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    // 樣式
        li{list-style: none;}
        div span.grade{width: 80px;height: 40px;font: 20px/40px "";float: left;;background: deepskyblue;border: none;border-radius: 5px;color: #fff;text-align: center;margin-bottom: 10px;}
        div .start{width: 80px;height: 40px;font: 20px/40px "";float: left;margin-right: 30px;background: deepskyblue;border: none;border-radius: 5px;color: #fff;outline: none;}
        div i{float: left;height: 40px;width:100px;font:26px/40px "";text-align: center;}
        div span.level2{width: 80px;height: 40px;font: 20px/40px "";float: left;background: deepskyblue;border: none;border-radius: 5px;color: #fff;text-align: center;margin-bottom: 10px;margin-right: 10px;}
        div li:nth-of-type(3) input{width: 30px;height: 40px;font: 20px/40px "";outline: none;background: deepskyblue;border: none;border-radius: 5px;color: #fff;text-align: center;margin: 0 8px;}
        div li:nth-of-type(3) i{
        width: 30px;height: 30px;font: 20px /30px "";text-align: center;border: 0;float: left;
        }
    </style>
</head>
<body>
    <div>
        <ul>
            <li><span class="grade">分?jǐn)?shù)</span><i></i></li>
            <li><input type="button" value="開始" class="start"></li>
            <li><span class="level2">難度</span><input type="button" value="-" class="sub"><i class="level">1</i><input type="button" value="+" class="add"></li>
        </ul>
    </div>
</body>
<script>
    class Game{
        constructor(co) {
            //背景圖默認(rèn)樣式
            this.desktop = {
                h:400,
                w:800,
                c:'#999'
            };
            //食物默認(rèn)樣式
            this.food = {
                h:20,
                w:20,
                c:'green'
            };
            //貪吃蛇初始樣式
            this.snake = {
                w:20,
                h:20,
                c:'red',
                direct:'right'
                // speed:300,
            }
            //蛇身建立數(shù)組
            this.pos=[{x:5,y:3,c:'red'},{x:4,y:3,c:randomColor()},{x:3,y:3,c:randomColor()}];
            this.grade = 0;
            if(co){
                this.init();
            }
        }
        init(){
            this.desktopInit();
            this.foodInit();
            this.snakeInit();
        }
        // 背景初始
        desktopInit(){
            this.desktop.ele = document.createElement('div');
            this.desktop.ele.style.cssText = `width:${this.desktop.w}px;height:${this.desktop.h}px;background:${this.desktop.c};margin:10px auto;position: relative;`;
            document.body.appendChild(this.desktop.ele);
        }
        // 食物初始
        foodInit(){
            this.food.ele = document.createElement('div');
            this.food.ele.style.cssText = `width:${this.food.w}px;height:${this.food.h}px;background:${this.food.c};position: absolute;`;
            this.desktop.ele.appendChild(this.food.ele);
            this.foodVal();
        }
        // 食物隨機定位坐標(biāo)
        foodVal(){
            this.food.x = random(0,(this.desktop.w/this.food.w-1));
            this.food.y = random(0,(this.desktop.h/this.food.h-1));
            this.foodPlace();
        }
        // 食物定位 以及不生成在蛇身
        foodPlace(){
            for(var i = 0;i<this.pos.length;i++){
                if(this.food.x == this.pos[i].x && this.food.y == this.pos[i].y){
                    this.foodVal();
                    return;
                }
            }
            this.food.l = this.food.x*this.food.w;
            this.food.t = this.food.y*this.food.h;
            this.food.ele.style.left = this.food.l + "px";
            this.food.ele.style.top = this.food.t + "px";
        }
        // 蛇身初始
        snakeInit(){
            for(var i = 0;i<this.pos.length;i++){
                if(!this.pos[i].ele){
                    this.pos[i].ele = document.createElement('div');
                    this.pos[i].ele.style.cssText = `width:${this.snake.w}px;height:${this.snake.h}px;background:${this.pos[i].c};position: absolute;`;
                    this.desktop.ele.appendChild(this.pos[i].ele);
                }
                this.pos[i].ele.style.left = this.pos[i].x * this.snake.w + "px";
                this.pos[i].ele.style.top = this.pos[i].y * this.snake.h + "px";
            }
            clearTimeout(this.snake.t);
            // 移動一次 渲染頁面一次
            this.snake.t = setTimeout(() => {
                this.snakeMove();
            },speed);
        }
        // 蛇身移動
        snakeMove(){
            for(var i = this.pos.length-1;i>0;i--){
                this.pos[i].x = this.pos[i-1].x;
                this.pos[i].y = this.pos[i-1].y;
            }
            this.snakeHead();
            this.snakeInit();
            this.addEvent();
            this.eatFood();
            this.deadWay();
        }
        // 添加鍵盤事件
        addEvent(){
            var that = this;
            document.onkeydown = function (eve) {
                var e = eve || window.event;
                var keyCode = e.keyCode || e.which;
                that.direction(keyCode);
            }
        }
        // 蛇身運動方向 且不許反方向按鍵
        direction(eve){
            if(this.snake.direct== 'left' && eve == 39){
                eve = 37;
            }else if(this.snake.direct== 'top' && eve == 40){
                eve = 38;
            }else if(this.snake.direct== 'right' && eve == 37){
                eve = 39;
            }else if(this.snake.direct== 'bottom' && eve == 38){
                eve = 40;
            }
            switch(eve){
                case 37: this.snake.direct = 'left';break;
                case 38: this.snake.direct = 'top';break;
                case 39: this.snake.direct = 'right';break;
                case 40: this.snake.direct = 'bottom';break;
            }
        }
        // 蛇頭轉(zhuǎn)向
        snakeHead(){
            switch(this.snake.direct){
                case 'left' :this.pos[0].x -= 1;break;
                case 'top' :this.pos[0].y -= 1;break;
                case 'right' :this.pos[0].x += 1;break;
                case 'bottom' :this.pos[0].y += 1;break;
            }
        }
        // 吃到食物,身體長度++,刷新食物位置
        eatFood(){
            if(this.pos[0].x == this.food.x && this.pos[0].y == this.food.y){
                this.grade ++;
                grade.innerHTML = this.grade;
                this.pos.push({
                    x:this.pos[this.pos.length-1].x,
                    y:this.pos[this.pos.length-1].y,
                    c:randomColor()
                });
                this.foodVal();
            }
        }
        // 尋死方式
        deadWay(){
            this.wall();
            this.eatSelf();
        }
        wall(){
            if(this.pos[0].x<0||this.pos[0].x>this.desktop.w/this.snake.w-1||this.pos[0].y<0||this.pos[0].y>this.desktop.h/this.snake.h-1){
                clearTimeout(this.snake.t);
                alert('撞墻了');
                this.gameOver();
            }
        }
        eatSelf(){
            for(var i = 1;i<this.pos.length;i++){
                if(this.pos[0].x == this.pos[i].x && this.pos[0].y == this.pos[i].y){
                    clearTimeout(this.time);
                    alert('撞到自己了');
                    this.gameOver();
                }
            }
        }
        // Gameover
        gameOver(){
            clearTimeout(this.snake.t);
            this.desktop.ele.innerHTML = '';
            this.desktop.ele.remove();
            type = 0;
        }
    }
    var start = document.querySelector('.start');
    var grade = document.querySelector('div i');
    var sub = document.querySelector('.sub');
    var add = document.querySelector('.add');
    var level = document.querySelector('.level');
    var type = 0;
    var speed = 300;
    var a = new Game();
    start.onclick = function () {
        if(type == 0){
            a = new Game(1);
            grade.innerHTML = '0';
            type = 1;
        }
    }
    if(type == 0){
        sub.onclick = function () {
            if(speed >= 300){
                speed = 300;
                level.innerHTML = '1';
            }else{
                speed +=50; 
                level.innerHTML --;
            }
        }
        add.onclick = function () {
            if(speed<=50){
                speed =50;
                level.innerHTML = '6';
            }else{
                speed -=50; 
                level.innerHTML ++ ;
            }
        }

    }

    function random(a,b) {
        return Math.round(Math.random()*(a-b)+b);
    }
    function randomColor() {
        return  `rgb(${random(0,255)},${random(0,255)},${random(0,255)})`;
    }

</script>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容