1、关键代码
function Square(x, y, classname) {
this.x = x * sw;
this.y = y * sh;
this.class = classname;
this.viewContent = document.createElement('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;
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 文件夹