使用面向對象思想實現貪喫蛇食物的功能

<style type="text/css">
		*{
			margin:0;
			padding:0;
		}
		#map{
			width:800px;
			height:600px;
			position:relative;
			border:1px solid #ccc;
		}
	</style>
<body>
	<div id="map"></div>
</body>
<script type="text/javascript">
		window.οnlοad=function(){
			var oMap=document.getElementById("map");
			function Random(){}
			//在原型中添加方法:獲取隨機數用來表示食物的座標
			Random.prototype.getrandom=function(min,max){
				return Math.floor(Math.random()*(max-min)+min);
			};
			window.random=new Random();
			function food(width,height,color){//食物進行初始化			
				this.width=width;
				this.height=height;
				this.color=color;
			}
			food.prototype.show=function(map){//食物在畫布中如何顯示
				this.element=document.createElement("div");
				var oDiv=this.element;
				oMap.appendChild(oDiv);
				oDiv.style.width=this.width+"px";
				oDiv.style.height=this.height+"px";
				oDiv.style.backgroundColor=this.color;
				oDiv.style.position="absolute";
				fd.where(oMap);
			};
			food.prototype.where=function(map){
				var x=random.getrandom(0,(map.offsetWidth/this.width))*this.width;
				var y=random.getrandom(0,(map.offsetHeight/this.height))*this.height;
				var oDiv=this.element;
				oDiv.style.left=x+"px";
				oDiv.style.top=y+"px";
			};
			var fd=new food(20,20,"red");
			fd.show(oMap);
		};
	</script>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章