面向对象贪吃蛇游戏源码

话不多说,直接上代码。面向对象纯用JS做一个贪吃蛇

html代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/snake.css">

</head>

<body>
    <div class="content">
        <button class="btn startBtn"></button>
        <button class="btn pauseBtn"></button>
        <div id="snakeWarp">
            <!-- <div class="snakehead"></div>
            <div class="snakebody"></div>
            <div class="snakefood"></div> -->
        </div>
    </div>


    <script src="./js/snake.js">
    </script>
</body>

</html>

Css代码部分

body{
    overflow: hidden;
}
.content {
    width: 640px;
    height: 640px;
    margin: 50px auto;
    position: relative;
    background: rgb(3, 164, 204);
    box-sizing: border-box;
    border: 20px solid rgb(12, 214, 170);
}

.btn {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 3;
}

.startBtn {
    background: url(../img/12.png) no-repeat center;
    background-size: 200px 100px;
    outline: none;
    border: none;
}

.pauseBtn {
    width: 50px;
    height: 50px;
    background: url(../img/19e891a9cd0953a9b68bd74fac8e4e17.jpg) no-repeat center;
    background-size: 50px 50px;
    display: none;
}

#snakeWarp {
    width: 600px;
    height: 600px;
    background: rgb(9, 127, 223);
}

#snakeWarp div {
    width: 20px;
    height: 20px;
}

.snakeHead {
    background: url(../img/13.jpeg) no-repeat center;
    background-size: 100%;
    border-radius: 50%;
    transform: rotate(-90deg);
}

.snakeBody {
    background: green;
    border-radius: 50%;
}

.snakeFood {
    background: url(../img/14.jpeg) no-repeat center;
    background-size: 100%;
    border-radius: 50%;
}

##最重要的JS文件

//面相对象 写贪吃蛇。
var sw = 20, //方块的 宽高 跟列数
    sh = 20,
    tr = 30,
    td = 30;

var snake = null, //蛇的实例
    food = null, //食物的实例
    game = null; //游戏的实例
//方块构造函数。
//声明一个方块 传入三个参数 坐标 跟 名字 
function Square(x, y, classnames) {
    //用来获得 实际传入的x  y 的转成实际坐标
    this.x = sw * x;
    this.y = sh * y;
    this.class = classnames;
    //创建一个实际小方块 方块对应的 dom元素 
    this.viewContent = document.createElement('div');
    //给她添加一个实际的class 名字 是上面参数传入的class
    this.viewContent.className = this.class;
    //方块的父级元素
    this.parent = document.getElementById('snakeWarp');
}
//创建方块dom元素 
Square.prototype.create = function () {
    this.viewContent.style.position = "absolute";
    this.viewContent.style.width = sw + 'px';
    this.viewContent.style.height = sh + "px";
    this.viewContent.style.left = this.x + "px";
    this.viewContent.style.top = this.y + "px";
    this.parent.appendChild(this.viewContent); //把创建的方块元素 添加到父亲的元素中 

}
Square.prototype.remove = function () {
    //删除元素 的方法 
    this.parent.removeChild(this.viewContent);
};
//创建一个蛇类
function Snake() {
    this.head = null; //存一下蛇头的信息
    this.tail = null; //存一下蛇尾的信息
    this.pos = []; //存一下方块上的所有信息 里面是一个二维数组 用来下面 下一个坐标的四个判断
    this.directionNum = {
        up: {
            x: 0,
            y: -1,
            rotate: -90 //蛇头在不同方向进行旋转 
        },
        right: {
            x: +1,
            y: 0,
            rotate: 0 //蛇头在不同方向进行旋转 
        },
        left: {
            x: -1,
            y: 0,
            rotate: 180 //蛇头在不同方向进行旋转 
        },
        down: {
            x: 0,
            y: +1,
            rotate: 90 //蛇头在不同方向进行旋转 
        }

    } //蛇的下一步的方向 
}
//初始化一个对象 init 初始化 蛇的一些属性
Snake.prototype.init = function () {
    //蛇头 
    var snakeHead = new Square(2, 0, 'snakeHead');
    snakeHead.create();
    this.head = snakeHead; //存储蛇头的信息 
    this.pos.push([2, 0]); //存储这个方块的位置信息 也就是蛇头的位置信息
    //蛇身体 
    var snakeBody1 = new Square(1, 0, 'snakeBody')
    snakeBody1.create();
    this.pos.push([1, 0]); //同样把 舍身体的一的坐标存起来 
    var snakeBody2 = new Square(0, 0, 'snakeBody')
    snakeBody2.create();
    this.tail = snakeBody2;
    this.pos.push([0, 0]);
    //有一个链表结构  就是前后 关系 
    snakeHead.last = null; //前一节身体
    snakeHead.next = snakeBody1; //后一节身体
    //第二个身体的前后关系
    snakeBody1.last = snakeHead;
    snakeBody1.next = snakeBody2;
    //第三个身体的前后关系
    snakeBody2.last = snakeBody1;
    snakeBody2.next = null;
    //蛇头的初始化 方向
    this.direction = this.directionNum.right
}
//获取 蛇头下一个位置对应的元素 ,根据元素  做一些不同的事情 
Snake.prototype.getNextPos = function () {
    // 下一个点的坐标
    var nextPos = [
        this.head.x / sw + this.direction.x, //蛇头x的坐标  后面要加方向的位置再算坐标
        this.head.y / sh + this.direction.y //蛇头y的坐标 后面要加什么?
    ]
    //做判断 下一个点的种种情况 
    //下一个点是 自己,代表装到自己 游戏结束
    var selfCollide = false; //默认不是撞到自己 
    this.pos.forEach(function (value) {
        if (value[0] == nextPos[0] && value[1] == nextPos[1]) {
            //如果数组中的两个数据都相等,就说明下一个点在能在蛇神体里面找到 就代表装到自己了
            selfCollide = true
        }
    });
    if (selfCollide == true) {
        // console.log('游戏结束,撞到了自己');
        this.strategies.die();
        return;
    }

    //下个点是墙 代表游戏结束 撞到了围墙 
    if (nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > (td - 1) || nextPos[1] > (tr - 1)) {
        // console.log("撞墙了宝贝。");
        this.strategies.die();
        return;
    }
    //下个点是 食物 就吃 这个条件成立说明 蛇头下一个点 就是食物 那个点 所以就执行吃
    if (food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]) {
        console.log('我吃到你了');
        this.strategies.eat.call(this);
        return;
    }

    //下个点啥都没有 就走 
    this.strategies.move.call(this); //改变this指向 继续让 this指向实例
}

//处理碰撞之后要做的事情 
Snake.prototype.strategies = {
    move: function (format) { //这个参数决定要不要删除 这个蛇尾  传这个参数就代表吃,不穿就代表走
        //重点 核心
        var newBody = new Square(this.head.x / sw, this.head.y / sh, 'snakeBody');
        //更新链表的关系
        newBody.next = this.head.next; //通过蛇头的链表结构 获取到上面元素的后面哪一个蛇身体 因为现在蛇头还没有被移除 所以可以
        newBody.next.last = newBody;
        newBody.last = null;
        this.head.remove();
        newBody.create();
        //创建一个新的蛇头在原来的下一个点的坐标位置
        var newHead = new Square(this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y, 'snakeHead')
        //更新链表关系 
        newHead.next = newBody;
        newHead.last = null;
        newBody.last = newHead;
        newHead.viewContent.style.transform = 'rotate(' + this.direction.rotate + 'deg)';
        newHead.create();

        //pos 坐标也要更新了 身上的每一个坐标也要更新
        this.pos.splice(0, 0, [this.head.x / sw + this.direction.x, this.head.y / sh + this.direction.y]);
        // this.head 的信息 更新一下;
        this.head = newHead;

        if (!format) { //如果为format 为false 是需要删除 也就是除了吃之外所有的的都要删除
            this.tail.remove();
            this.tail = this.tail.last;
            this.pos.pop(); //删掉最后一个元素 
        }



        console.log(this);
        console.log('走了走了');
    },
    eat: function () {
        this.strategies.move.call(this, true); //因为 this还是 实例对象 所以把 this传到move里面让move里面的this指向实例对象
        console.log('吃呀吃'); //true 这个参数就是format  就代表 吃了 就代表不删除最后一个元素
        createFood();
        game.score++;
    },
    die: function () {
        console.log('游戏结束,撞到了自己');
        game.over();
    }
}


snake = new Snake();
// snake.init();
// snake.getNextPos();

//创建一个食物 类
function createFood() {
    var x = null;
    var y = null; //食物小方块的坐标

    var include = true; //循环跳出的条件,true 表示随机生成的坐标 在蛇身上 继续循环 flase 表示食物的坐标不再蛇身上 
    while (include) {
        x = Math.round(Math.random() * (td - 1));
        y = Math.round(Math.random() * (tr - 1));
        console.log(x);
        console.log(y);
        snake.pos.forEach(function (value) {
            if (x != value[0] && y != value[1]) {
                include = false; //这个表明这个随机生成的坐标在蛇身上并没有被找到。
            }
        });
    }

    //生成食物 
    food = new Square(x, y, "snakeFood");
    food.pos = [x, y]; //存储生成食物的坐标用于 跟蛇头要走的下一个点 做对比
    //数据结构单例模式 比较高效  只是改变 food的坐标 并不是每次都生成一个新的然后删除原来的食物
    var foodDom = document.querySelector('.snakeFood');
    if (foodDom) {
        foodDom.style.left = x * sw + 'px';
        foodDom.style.top = y * sh + 'px';
    } else {
        food.create();
    }
    // food.create();
}

//创建一个游戏的规则 
function Game() {
    this.timer = null; //时间
    this.score = 0; //得分 
}
Game.prototype.init = function () {
    snake.init();
    createFood();
    snake.getNextPos();


    //给键盘事件 
    document.onkeydown = function (ev) {
        // console.log(ev.which);
        //用户按下 左键的时候这个蛇的方向不能是往右边 才能往左边走;
        if (ev.which == 37 && snake.direction != snake.directionNum.right) { //左键 向左边走 
            snake.direction = snake.directionNum.left;
        } else if (ev.which == 38 && snake.direction != snake.directionNum.down) { //上面
            snake.direction = snake.directionNum.up;
        } else if (ev.which == 39 && snake.direction != snake.directionNum.left) { //右边
            snake.direction = snake.directionNum.right;
        } else if (ev.which == 40 && snake.direction != snake.directionNum.up) { //下边
            snake.direction = snake.directionNum.down;
        }
    }
    this.start();
}
Game.prototype.start = function () { //开始游戏
    this.timer = setInterval(function () {
        snake.getNextPos(); //获取下一个点;
    }, 200) //这个就可以控制设移动的速度
}
Game.prototype.over = function () {
    clearInterval(this.timer);
    alert('你的得分为' + this.score);
    //游戏归零 
    var snakeWarp = document.getElementById('snakeWarp');
    snakeWarp.innerHTML = "";
    snake = new Snake(); //初始化实例对象 
    var startBtnWrap = document.querySelector('.startBtn');
    startBtnWrap.style.display = "block";

}
Game.prototype.pause = function () {
    clearInterval(this.timer);
}
//游戏开始 
var startBtn = document.querySelector('.startBtn');
startBtn.onclick = function () {
    startBtn.style.display = "none";
    game = new Game();
    game.init();

}

//暂停功能
var snakeWarp = document.getElementById('snakeWarp');
var pauseBtn = document.querySelector('.pauseBtn');
snakeWarp.onclick = function () {
    game.pause();
    pauseBtn.style.display = 'block';
}
pauseBtn.onclick = function () {
    game.start();
    pauseBtn.style.display = 'none';
}

注释写的都很清楚,此面向对象变成 参考网上的渡一写的,仅当资料供大家参考。想要了解详细的过程的 可以自行百度。此游戏还有些许不完美跟BUG望大佬们帮忙优化指正。谢谢大佬们~。。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值