Web前端之实现贪吃蛇、创建与获取元素、getElementById、createElement、querySelector、forEach、random、Math
Web前端之实现贪吃蛇、创建与获取元素、getElementById、createElement、querySelector、forEach、random、Math
·
关键代码
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();
}
}
完整代码
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)