JavaScript—対象に向かってへびを食べる。2食べ物の対象

1538 ワード

原文のリンク:http://www.cnblogs.com/ruogu/p/10836765.html
食べ物の対象
//   
(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)

}
  
転載先:https://www.cnblogs.com/ruogu/p/10836765.html