网页贪吃蛇之随机小方块

11 篇文章 0 订阅

通过原型来实现效果
原型(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"));
    })())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值