面向对象实现网页版简易贪吃蛇

说明:

  • 游戏可以选择不同的难度
  • 贪吃蛇吃到一个食物计分为一
  • 初始长度为三,分别代表贪吃蛇的头尾巴身体
  • 撞到自己或者撞到墙壁就结束

js代码如下:

         class Map{//地图类
            constructor(){
                this.w=600;//动态生成地图的长宽
                this.h=400;
                this.num=0;//记录分数
                this.init();
            }
            init(){
                this.map=document.createElement("div");
            this.map.style.cssText=`width:${this.w}px;height:${this.h}px;margin:20px auto;background:#eee;border:1px solid #000;position:relative`;
                document.body.appendChild(this.map);
                
            }
            grade(){//记录分数
                this.gradeBox=document.createElement("div");
                this.gradeBox.className="grade";
                this.map.appendChild(this.gradeBox);
                var str=`
                分数:
                <span class="num">0</span>    
                `;
                this.gradeBox.innerHTML=str;
                this.gradeBox.children[0].innerHTML=this.num;
            }
        }
        class Food{//食物类
            constructor(){
                this.w=20;
                this.h=20;
                this.c=randomColor();
            }
            init(){
                this.food=document.createElement("div");
                this.food.style.cssText=`width:${this.w}px;height:${this.h}px;background:${this.c};position:absolute`;
                this.left=random(0,(map.w-this.w)/this.w);
                this.top=random(0,(map.h-this.h)/this.h);
                this.food.style.left=this.left*this.w+"px"
                this.food.style.top=this.top*this.h+"px"
                map.map.appendChild(this.food);
            }
        }
        class Snake{//贪吃蛇
            constructor(){
                this.w=20;
                this.h=20;
                this.d="right";
                this.position=[
                    {
                        ele:null,
                        x:3,
                        y:2,
                        c:randomColor()
                    },
                    {
                        ele:null,
                        x:2,
                        y:2,
                        c:randomColor()
                    },
                    {
                        ele:null,
                        x:1,
                        y:2,
                        c:randomColor()
                    }
                ]
            }
            init(){
                for(var i=0;i<this.position.length;i++){
                    if(!(this.position[i].ele)){
                        this.position[i].ele=document.createElement("div");
                        map.map.appendChild(this.position[i].ele);
                    }
                    this.position[i].ele.style.cssText=`width:${this.w}px;height:${this.h}px;background:${this.position[i].c}; position:absolute;left:${this.position[i].x*this.w}px;top:${this.position[i].y*this.h}px`;

                }
                 
                this.t=setTimeout(()=>{
                    this.move();
                },parseInt(select.dif)*100);
            }
            move(){//贪吃蛇的移动
                //所有元素跟随蛇头移动
                for(var i=this.position.length-1;i>0;i--){
                    this.position[i].x=this.position[i-1].x;
                    this.position[i].y=this.position[i-1].y;
                }
                switch(this.d){//判断蛇的移动方向
                    case "left":this.position[0].x-=1;break;
                    case "top":this.position[0].y-=1;break;
                    case "right":this.position[0].x+=1;break;
                    case "bottom":this.position[0].y+=1;break;
                }
                //  吃到食物
                if(this.position[0].x==food.left&&this.position[0].y==food.top){
                     this.position.push({
                         ele:null,
                         x:this.position[2].x,
                         y:this.position[2].y,
                         c:randomColor()
                     })
                     map.num++;
                     map.gradeBox.children[0].innerHTML=map.num;
                     food.food.remove();
                     food.init();
                }
                if(this.position[0].x<0||this.position[0].x>((map.w-this.w)/this.w)||this.position[0].y<0||this.position[0].y>(map.h-this.h)/this.h){
                    alert("撞墙了");
                    return;
                }
                for(var i=1;i<this.position.length;i++){
                    if(this.position[0].x==this.position[i].x&&this.position[0].y==this.position[i].y){
                        alert("撞到自己了");
                        return;
                    }
                }
                this.init();
            }
            direct(code){//蛇头的移动方向不允许立即改变
                switch(code){
                    case 37:
                        if(this.d=="right") break;
                        this.d="left";break;
                    case 38:
                        if(this.d=="bottom") break;
                        this.d="top";break;
                    case 39:
                        if(this.d=="left") break;
                        this.d="right";break;
                   
                    case 40:
                        if(this.d=="top") break;
                        this.d="bottom";break;
                }

            }
            
        }
         
        
        class Select{//选择难度界面
            constructor(){
                this.w=300;
                this.h=400;
                setTimeout(() => {
                    this.sbox.style.opacity=1;
                }, 200);
                this.init();
                
            }
            init(){
                this.sbox=document.createElement("div");
                this.sbox.style.cssText=`width:${this.w}px;height:${this.h}px;position:absolute;top:0;left:150px;display:flex;justify-content:space-around;flex-direction:column;align-items:center;transition:all 0.6s; opacity:0`;
                map.map.appendChild(this.sbox);
                var str=`
                    <div class="inner" id="title">请选择难度</div>
                    <div class="inner difficult"   index="3">简单</div>
                    <div  class="inner difficult"   index="2"> 一般</div>
                    <div class="inner difficult"   index="1">困难</div>
                `
                this.sbox.innerHTML=str;
                this.addEvent();
                
            }
            addEvent(){
                var that=this;
                this.sbox.onclick=function(eve){
                    var e=eve||window.event;
                    var target=e.target||e.srcElement;
                    if(target.className=="inner difficult"){
                        that.dif=target.getAttribute("index");//设置难度
                        this.style.opacity=0;
                        food.init();
                        snake.init();
                        map.grade();
                    }

                }
            }
        }
        var map=new Map();
        var food=new Food();
        var snake=new Snake();
        var select=new Select();

        document.onkeydown=function(eve){
            var e=eve||window.event;
            var code=e.keyCode||e.which||e.charCode;
            snake.direct(code);
        }

    

        //封装食物的随机位置和蛇节的随机颜色值
        function random(min,max){
            return Math.floor(Math.random()*(max-min+1)+min);
        }
        function randomColor(){
            return `rgba(${random(0,255)},${random(0,255)},${random(0,255)}) `;
        }

以下为css代码:

由于地图食物和蛇都是动态生成,这里的css代码是选择难度界面以及计算分数界面

        #title{
            width:150px;
        }
        .inner{
            width: 100px;
            height: 40px;
            background: #999;
            border-radius:10px;
            line-height: 40px;
            text-align: center;
            font-weight: bold;
            cursor: pointer;
            /* opacity: 0; */
        }
        .grade{
           width:60px;
           height:40px;
           position:absolute;
           top:2px;left:2px; 
           font-size:14px;
           color:#666;
        }
        .num{
            color:#000;
        }

不足之处请大家留言,谢谢O(∩_∩)O~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容

  • 前言 这两天在网上看到一张让人涨姿势的图片,图片中展示的是贪吃蛇游戏, 估计大部分人都玩过。但如果仅仅是贪吃蛇游戏...
    派派森森阅读 5,423评论 0 0
  • 我开始懂得了《平凡的世界》里的孙少平 以前最看不惯他那眼高手低的做派 只不过书读的多些,自命清高 现在逐渐觉得 少...
    十四日省阅读 114评论 0 1
  • 世界那么大,能做的事情那么多,哪有时间跟烂人烂事絮絮叨叨。当自己没过上另一种生活的时候,别一刀地敌视着对方,决...
    孤独是孤独者的盛装阅读 353评论 0 0
  • 孩子的阅读习惯和老师的要求有很大的关系,我和孩子的的妈妈也都知道一个老师对孩子的影响有多么的重要,一切都感恩于你-...
    鱼儿哥哥阅读 557评论 0 1
  • 又是烟头,我每次看到它都不想捡。它静悄悄地呆在路边,一动也不动,显得那么微不足道,又楚楚可怜。要不是有人喊我停下,...
    月夕花晨XLN阅读 107评论 0 0