原生JS写的贪吃蛇

我用的面向对象的做法HTML标签用的就比较少了。

<div class="Box">
		<div class="btn" id="start"><button type="button"></button></div>
		<div class="btn" id="suspend"><button type="button"></button></div>
		<div id="Wrap">
			<!-- <div class="Sonke_Head"></div>
			<div class="Sonke_Body"></div>
			<div class="Food"></div> -->
		</div>
	</div>

这是CSS代码块,背景图片的地方需自己准备

*{
    margin: 0;
    padding: 0;
}
/* 外边大盒子 */
.Box{
    width: 800px;
    height: 680px;
    margin: 0 auto;
    position: relative;
}
/* 标题小盒子 */
.Box .box{
    width: 780px;
    height: 100px;
    margin: 0 auto;
    text-align: center;
    line-height: 100px;
}
input{
    width: 100px;
}
.Time{
    width: 220px;
}
/* 开始与暂停 */
.Box .btn{
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: rgba(68, 66, 64, 0.3);
    z-index: 2;
}
.Box .btn button{
    background: none;
    border: none;
    background-size: 100% 100%;

    cursor: pointer;
    outline: none;

    position: absolute;
    left: 50%;
    top: 50%;
}
.Box .begin button{
    width: 200px;
    height: 80px;
    background-image: url(../image/start1.jpg);
    border-radius: 20px;
    margin-left: -100px;
    margin-top: -40px;
}
.Box .suspend{
    display: none;
}
.Box .suspend button{
    width: 80px;
    height: 80px;
    background-image: url(../image/suspend.jpg);
    margin-top: -40px;
    margin-left: -40px;
}
/* Snake贪吃蛇 */
#parent{
    width: 780px;
    height: 560px;
    background-color: #008c8c;
    border: 10px solid #000;
    position: relative;
}
/* #parent div{
    width: 20px;
    height: 20px;
} */
.snakeHead{
    background-image: url(../image/Snakehead.gif);
    background-size: 100%;
    border-radius: 5px;
}
.snakeBody{
    background-color: #9ddbb1;
    border-radius: 50%;
}
.food{
    background-image: url(../image/egg.png);
    background-size: 100%;
    border-radius: 50%;
}

这里我用的JavaScript的面向对象写的,面向对象相对面向过程更加简单,花了一个下午写的有什么改进的地方请指教


//定义全局变量
var score = document.getElementsByClassName('score')[0];//分数
var maxscore = document.getElementsByClassName('Maxscore')[0];//最高分
var time = document.getElementsByClassName('Time')[0];
var difficulty = document.getElementsByClassName('difficulty')[0];//难度程度
var Arr = [];
var wh = 20,//小方块的宽度
    hh = 20,//小方块的高度
    tr = 28, //代表行块
    td = 39 //代表列块

var snake = null,//蛇的实例化对象
    food = null,//食物的实例化对象
    game = null;//游戏的实例化对象

//创建小方块的构造函数
function Square(x,y,classname){
    //0,0       0,0
    //20,0      1,0         20,20   1,1
    this.x = x * wh;
    this.y = y * hh;
    this.class = classname;
    
    this.box = document.createElement('div');//创建一个盒子
    this.box.className = this.class;//赋值Classname值;
    this.parent = document.getElementById('parent');//获取盒子的父级
};
//将dom元素添加到页面中
Square.prototype.create = function(){
    this.box.style.position = 'absolute';
    this.box.style.width = wh + 'px';//盒子的宽度
    this.box.style.height = hh + 'px';//盒子的高度
    this.box.style.left = this.x + 'px';//盒子的x位置
    this.box.style.top =  this.y + 'px';//盒子的y位置

    this.parent.appendChild(this.box);
};
//将dom元素删除
Square.prototype.remove = function(){
    this.parent.removeChild(this.box);
};

//创建蛇
function Snake(){
    this.head = null;//蛇头的位置信息
    this.tail = null;//蛇尾的位置信息
    this.postion = [];//存一下蛇身的位置,苹果不能出现在蛇的身上,判断一下

    this.direction = {//蛇走的方向
        left : {
            x : -1,
            y : 0,
            rotate : 180,
        },
        right : {
            x : 1,
            y : 0,
            rotate : 0,
        },
        top : {
            x : 0,
            y : -1,
            rotate : -90,
        },
        button : {
            x : 0,
            y : 1,
            rotate : 90,
        }
    }
};
//初始化
Snake.prototype.init = function(){
    //创建蛇头
    var snakeHead = new Square(2,0,'snakeHead');
        snakeHead.create();
    this.head = snakeHead;//存一下蛇头信息
    this.postion.push([2,0]);//存一下蛇头位置
    
    //创建蛇的身体body1
    var snakeBody1 = new Square(1,0,'snakeBody');
        snakeBody1.create();
    this.postion.push([1,0]);//存一下蛇身的位置

    //创建蛇的身体Boxy2
    var snakeBody2 = new Square(0,0,'snakeBody');
        snakeBody2.create();
    this.tail = snakeBody2;
    this.postion.push([0,0]);

    //蛇身形成链表关系
    snakeHead.rig = null;
    snakeHead.lef = snakeBody1;

    snakeBody1.rig = snakeHead;
    snakeBody1.lef = snakeBody2;

    snakeBody2.rig = snakeBody1;
    snakeBody2.lef = null;

    //给蛇添加一条默认蛇走的方向
    this.dir = this.direction.right;//右
};
//下一个位置的情况作出相对的情况反应;
Snake.prototype.getpostion = function(){
    //下一步的位置
    var nextPos = [
        this.head.x/wh + this.dir.x,
        this.head.y/hh + this.dir.y
    ];
    
    //下一个位置是自己的身体,代表撞到了自己
    var selfCollied = false ; //默认情况下不是
    this.postion.forEach(function(value){
        if(value[0] == nextPos[0] && value[1] == nextPos[1]){
            //如果数组中的两个数据都相等,就说明下一个位置是自己
            selfCollied = true;
        }
    });

    if(selfCollied){
        this.strategies.die.call(this);
        return;
    }
    //下一个位置是墙,游戏结束
    if(nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0]>td-1 ||nextPos[1]>tr-1){
        this.strategies.die.call(this);
        return;
    }
    //下一个点是食物,把食物吃了
    if(food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]){
        //如果这个条件成立说明下一个位置是食物
        this.strategies.eat.call(this);
        return
    }
    //下一个点什么都不是,继续走
    this.strategies.move.call(this);
};
//处理碰撞后做的相对的反应
Snake.prototype.strategies = {
    move : function(format){//这个参数用于决定要不要删除蛇尾,
        //创建一个new身体(在旧蛇头的位置);
        var newBody = new Square(this.head.x/wh,this.head.y/hh,'snakeBody');
        //更新链表关系
        newBody.lef = this.head.lef;
        newBody.lef.rig = newBody;
        newBody.rig = null;

        this.head.remove();//把旧蛇头从原来的位置删除
            newBody.create();

        //创建一个新的蛇头(其实就是下一个位置)
        var newHead = new Square(this.head.x/wh + this.dir.x,this.head.y/hh + this.dir.y,'snakeHead');
        //更新列表关系
        newHead.lef = newBody;
        newHead.rig = null;
        newBody.rig = newHead;
        newHead.box.style.transform = 'rotate('+this.dir.rotate+'deg)';
        newHead.create();

        //蛇身上的每一个方块的坐标
        this.postion.splice(0,0,[this.head.x/wh + this.dir.x,this.head.y/hh + this.dir.y]);
        this.head = newHead; //更新蛇头的信息

        if(!format){//如果format的值为false,表示需要删除
            this.tail.remove();
            this.tail = this.tail.rig;

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

        //分数
        score.value = game.score;
        Arr.push(game.score);
        maxscore.value = Math.max.apply(null,Arr);
    },
    die : function(){
        game.over();
    }
};

snake = new Snake();

//创建食物
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.postion.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*wh + 'px';
        foodDom.style.top = y*hh +'px';
    }else{
        food.create();
    }
}

//创建游戏逻辑
function Game(){
    this.timer = null;//时间
    this.score = 0; //分数
}

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

    document.onkeydown = function(event){
        var e = event || window.event;
        var k = e.keyCode || e.which;
        if(k == 65 && snake.dir != snake.direction.right){
            snake.dir = snake.direction.left
        }else if(k == 87 && snake.dir != snake.direction.button){
            snake.dir = snake.direction.top;
        }else if(k == 68 && snake.dir != snake.direction.left){
            snake.dir = snake.direction.right;
        }else if(k == 83 && snake.dir != snake.direction.top){
            snake.dir = snake.direction.button;
        }
    }

    this.start();
}

Game.prototype.start = function(){//开始游戏
    this.timer = setInterval(function(){
        snake.getpostion();
    },200);
};

Game.prototype.pause = function(){
    clearInterval(this.timer);
};
//结束游戏
Game.prototype.over = function(){
    clearInterval(this.timer);
    alert('你的得分为:'+this.score+';你的最高得分是:'+maxscore.value);

    //游戏回到最初的状态
    var parent = document.getElementById('parent');
        parent.innerHTML = '';
        score.value = 0;

        snake = new Snake();
        game = new Game();

    var startBtnWrap = document.querySelector('.begin');
        startBtnWrap.style.display = 'block';
};
//开启游戏
game = new Game();
var startBtn = document.querySelector('.begin button');
    startBtn.onclick = function(){
        startBtn.parentNode.style.display = 'none';
        game.init();

        setInterval(function(){
            time.newTime(true);
        },1000)

    };

//暂停
var parent = document.getElementById('parent');
var suspend = document.querySelector('.suspend button');
    parent.onclick = function(){
        game.pause();
        suspend.parentNode.style.display = 'block';
    };
//继续
suspend.onclick = function(){
    game.start();
    suspend.parentNode.style.display = 'none';
};


//时间
function Complement(x){
    if(x<10){
        return '0' + x;
    }else{
        return x;
    }
}
function wek(x){
    var arr = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
    for(var i = 0;i<arr.length;i++){
        if(x == i){
            return arr[x];
        }
    }
}
Element.prototype.newTime = function(key){
    var date = new Date();
    var Year = date.getFullYear();
    var Month = date.getMonth()+1;
    var Day = date.getDate();
    var Hours = date.getHours();
    var Minutes = date.getMinutes();
    var Seconds = date.getSeconds();
    Day = Complement(Day);
    Hours = Complement(Hours);
    Minutes = Complement(Minutes);
    Seconds = Complement(Seconds);
    var Week = date.getDay();
    Week = wek(Week);
    if(key){
        this.value = Year+'年'+Month+'月'+Day+'日'+Hours+'时'+Minutes+'分'+Seconds+'秒'+Week;
    }else{
        this.innerHTML = Year+'年'+Month+'月'+Day+'日'+Hours+'时'+Minutes+'分'+Seconds+'秒'+Week;
    }
}

今日分享就到这里吧!不定时更新作品,有什么需要改进的地方还请指教,感谢各位大神支持


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值