JavaScript—面向对象 贪吃蛇_2 食物对象
食物对象
//自调用
(function (){
function Food(element) {
this.width = 20
this.height = 20
this.backgroundColor = '#ff8500'
this.x = 50
this.y = 50
this.elemen = element
this.arr = []
}
Food.prototype.remove=function() {
for (let i = 0; i < this.arr.length; i++) {
this.arr[i].parentNode.removeChild(this.arr[i])
this.arr.splice(i, 1)
}
}
Food.prototype.show = function () {
this.remove()
this.x = randomNum(0, (this.elemen.offsetWidth - this.width) / this.width) * this.width
this.y = randomNum(0, (this.elemen.offsetHeight - this.height) / this.height) * this.height
let div = document.createElement('div')
this.elemen.appendChild(div)
div.style.width = this.width + 'px';
div.style.height = this.height + 'px'
div.style.backgroundColor = this.backgroundColor
div.style.position = 'absolute'
div.style.left = this.x + 'px'
div.style.top = this.y + 'px'
this.arr.push(div)
console.log(this.arr)
}
//外部访问
window.Food = Food
})()
//随机
function randomNum(minNum, maxNum) {
return parseInt(Math.random() * (maxNum - minNum + 1) + minNum)
}

浙公网安备 33010602011771号