蛇对象
function Snake(element) { this.width = 20 this.height = 20 //蛇身 位置 颜色 this.body = [ {x: 6, y: 4, bc: 'red'}, {x: 5, y: 4, bc: 'blue'}, {x: 4, y: 4, bc: 'blue'}, ] this.direction = 'right' this.elemen = element //保存当前蛇 this.arr = [] } //吃食物 Snake.prototype.feed = function (food) { // 遇到食物 复制最后一个蛇身 if (this.body[0].x * this.width === food.x && this.body[0].y * this.height === food.y) { let o = this.body[this.body.length - 1] let pro = {x: o.x, y: o.y, bc: o.bc} this.body.push(pro) } } Snake.prototype.remove = function () { for (let i = 0; i < this.arr.length; i++) { this.arr[i].parentNode.removeChild(this.arr[i]) } this.arr = [] } //蛇出现 Snake.prototype.show = function () { this.remove() //console.log(this.arr) for (let i = 0; i < this.body.length; i++) { let div = document.createElement('div') this.elemen.appendChild(div) div.style.width = this.width + 'px'; div.style.height = this.height + 'px' div.style.position = 'absolute' div.style.backgroundColor = this.body[i].bc div.style.left = this.body[i].x * this.width + 'px' div.style.top = this.body[i].y * this.height + 'px' this.arr.push(div) } } //移动方法 Snake.prototype.udlr = function () { //蛇身移动 根据最后一个的位置等于上一个的位置 for (let i = this.body.length - 1; i > 0; i--) { this.body[i].x = this.body[i - 1].x this.body[i].y = this.body[i - 1].y } // 边界 let herfX = this.body[0].x * this.width >= this.elemen.offsetWidth - this.width || this.body[0].x * this.width <= 0 let herfY = this.body[0].y * this.height >= this.elemen.offsetHeight - this.height || this.body[0].y * this.height <= 0 if (herfX || herfY) { alert('完蛋') return } switch (this.direction) { case "right": { this.body[0].x += 1 break; } case "letf": { this.body[0].x -= 1 break; } case "up": { this.body[0].y -= 1 break; } case "down": { this.body[0].y += 1 break; } } }