ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

原生web实现贪吃蛇

2021-10-10 20:35:28  阅读:153  来源: 互联网

标签:原生 web rotate foodDom food 贪吃蛇 var function Math


目录


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 文件夹

标签:原生,web,rotate,foodDom,food,贪吃蛇,var,function,Math
来源: https://blog.csdn.net/weixin_51157081/article/details/120691603

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有