您当前的位置: 首页 > 

暂无认证

  • 0浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

原生web实现贪吃蛇

发布时间:2021-10-10 20:26:38 ,浏览量:0

目录
  • 1、关键代码
  • 2、完整代码
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 文件夹

关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.3492s