贪吃蛇之随机生成食物

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
	<title>Title</title>
<style>
    #map{
        width: 800px;
        height: 600px;
        background-color: #999;
        margin: 0 auto;
        position: relative;
    }
</style>
</head>
<body>
<div id="map"></div>
<script>
    //对象 : 随机数  , 小方块

//产生随机数的对象
((function () {
    //1 产生随机数的构造函数
    function Random(){

    }
    //2 在原型中添加方法
    Random.prototype.getRandom=function (min,max) {
        return parseInt(Math.random()*(max-min)+min)
    }
        //把局部对象暴露给window
    window.Random=Random;
})());
var rm=new Random()
console.log(rm.getRandom(10, 50));

//产生小方块
((function () {
    function Food(width,height,color,x,y) {
        this.width = width ||20;
        this.height=height||20;//默认小方块的宽高
        this.color=color||"red";
        //随机产生
        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.rander(map);
    }

    //产生随机的位置-->传地图
    Food.prototype.rander=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;

        this.element.style.left = this.x+"px"
        this.element.style.top = this.y+"px"



    }
    //实例化对象
    var food=new Food();
    food.init(document.getElementById("map"));
})());


</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44387746/article/details/86529675