第三天---随机小方块

随机小方块

❀随机小方块展示

html部分:

<div class="map"></div>

css样式:

.map{
width:800px;
height:600px;
background-image:#ccc;
position:relative;/*因为产生随机小方块就证明小方块是脱离文档流的,所以其父亲设置定位(子绝父相)*/
}

js代码:

<script>
//首先本次代码需要用到两个重点:(1)如何将局部变量转换成全局变量进行使用(2)明白自调用函数的作用---一次性函数(就是执行一次就失效)
(function(window){
	//定义产生在两个数之间的随机数的构造函数
	function Random(){
	}
	Random.prototype.getRandom=function(min,max){
		return Math.floor(Math.random()*(max-min)+min);
	}
	window.Random=new Random();
})(window);

//接下来是把随机产生的小方块当做对象,从而需要创建小方块的构造函数
(function(window){
var map=document.querySelector(".map");
	function Food(width,height,color){
		//这里之所以不传入小方块的横纵坐标是因为是随机产生的,所以无需用户进行输入;这里不需要传入元素对象是因为为了以后的操作
		this.width=width||20;
		this.height=height||20;
		this.color=color||"green";
		this.element=document.createElement("div");
		this.x=0;
		this.y=0;
		}
		//这个方法主要是对小方块的样式进行设置
		Food.prototype.init=function(map){
			var div=this.element;
			map.appendChild(div);
			div.style.position="absolute";//在这里一定要注意要给小方块也设置定位,不然页面将不会显示
			div.style.width=this.width+"px";//在这里进行设置宽度或者高度的时候一定不要忘记加“px”,不然将不会在页面上显示
			div.style.height=this.height+"px";
			div.style.backgroundColor=this.color;
			this.render(map);
			}
			Food.prototype.render=function(map){
				var div=this.element;
				var x=Random.getRandom(0,map.offsetWidth/this.width)*this.width;
				var y=Random.getRandom(0,map.offsetHeight/this.height)*this.height;
				this.x=x;
				this.y=y;
				div.style.left=this.x+"px";
				div.style.top=this.y+"px";
				}
			var food=new Food(20,20,"green");
			food.init(map);	
})(window);
</script>

在这里插入图片描述
在这里插入图片描述

❀经过测试发现随机小方块已经实现成功,并且小方块在随机的过程中也不会超过map的div的界限

这些其实都是很常见的一些案例,比如在贪吃蛇中的随机食物,就可以采用这个代码进行随机产生食物

猜你喜欢

转载自blog.csdn.net/qq_40181206/article/details/88430437
今日推荐