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)

}

  

posted @ 2019-05-09 09:53  跑着的小强  阅读(195)  评论(0编辑  收藏  举报