網頁貪喫蛇之隨機小方塊

通過原型來實現效果
原型(prototype)的優點:數據能夠共享,可以節省空間。

//佈局
 <style>
        #map{
            width: 800px;
            height: 600px;
            background-color: pink;
            position: relative;
        }
    </style>


<div id="map"></div>

實現效果的js代碼:

//函數的自調用:一次性調用,聲明的同時,直接調用
//產生隨機數的對象
    ((function () {
        function Random() {}
        
        //在原型中添加方法
        Random.prototype.getRandom = function (min,max) {
            return parseInt((Math.random() * (max - min) + min))
        }
        window.Random = Random;
    })())
    
	//實例化對象
    var rm = new  Random();

//產生小方塊的對象
    ((function () {
        function Food(width,height,color,x,y) {
            this.width = width || 20;
            this.height = height || 20;
            this.color = color || "green";
            //隨機產生的
            this.x = x || 0;
            this.y = y || 0;

            //創建一個div盒子
            this.element = document.createElement("div");
        }
        //設置小方塊顯示的效果和位置
        Food.prototype.init = function (map) {
            //1.儲存div元素的對象
            var div = this.element;
            //2.設置小方塊的樣式
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            div.style.backgroundColor = this.color;
            div.style.position = "absolute";
            //3.把小方塊添加到map中
            map.appendChild(div);

            //隨機的位置
            this.render(map);
        }

        //產生隨機的位置
        Food.prototype.render = function (map) {
            //隨機數的區間 0 - 39
            //隨機的座標
            this.x = rm.getRandom(0,map.offsetWidth / this.width) * this.width;
            this.y = rm.getRandom(0,map.offsetHeight / this.height) * this.height;
            console.log(this.y);
            console.log(rm.getRandom(0,map.offsetHeight / this.height) * this.height);
            this.element.style.left = this.x + "px";
            this.element.style.top = this.y + "px";
        }

        //實例化對象
        var food = new Food();
        food.init(document.getElementById("map"));
    })())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章