简易贪吃蛇(未考虑布局)原生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">分数</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) {
            //背景图默认样式
            this.desktop = {
                h:400,
                w:800,
                c:'#999'
            };
            //食物默认样式
            this.food = {
                h:20,
                w:20,
                c:'green'
            };
            //贪吃蛇初始样式
            this.snake = {
                w:20,
                h:20,
                c:'red',
                direct:'right'
                // speed:300,
            }
            //蛇身建立数组
            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();
        }
        // 食物随机定位坐标
        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;
            }
        }
        // 蛇头转向
        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>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容