原生web实现贪吃蛇


1、关键代码

function Square(x, y, classname) {
    
    
	// 0, 0		0, 0
    // 20, 0	1, 0
    // 40, 0	2, 0

    this.x = x * sw;
    this.y = y * sh;
    this.class = classname;

    // 方块对应的DOM元素
    this.viewContent = document.createElement('div');
    // 给div添加类
    this.viewContent.className = this.class;
    // 方块的父级,就是蛇身的父容器
    this.parent = document.getElementById('snakeWrap');
};

function Snake() {
    
    
    // 存一下蛇头的信息
    this.head = null;
    // 存一下蛇尾的信息
    this.tail = null;
    // 存储蛇身上的每一个方块的位置
    this.pos = [];

    // 存储蛇走的方向,用一个对象来表示
    this.directionNum = {
    
    
        left: {
    
    
            x: -1,
            y: 0,
            // 蛇头在不同的方向中应该进行旋转,要不始终是向右
            rotate: 180
        },
        right: {
    
    
            x: 1,
            y: 0,
            rotate: 0
        },
        up: {
    
    
            x: 0,
            y: -1,
            rotate: -90
        },
        down: {
    
    
            x: 0,
            y: 1,
            rotate: 90
        }
    }
};

function createFood() {
    
    
    // 食物小方块的随机坐标
    var x = null;
    var y = null;

    // 循环跳出的条件,true表示食物的坐标在蛇身上(需要继续循环)。
    // false表示食物的坐标不在蛇身上(不循环了)
    var include = true;
    while (include) {
    
    
        x = Math.round(Math.random() * (td - 1));
        y = Math.round(Math.random() * (tr - 1));

        snake.pos.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 * sw + 'px';
        foodDom.style.top = y * sh + 'px';
    } else {
    
    
        food.create();
    }
};

2、完整代码

gitee(码云) - mj01分支 - gluttonousSnake 文件夹

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/120691603