<!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><htmllang="ja"><head><metahttp-equiv="content-type"content="text/html;charset=utf-8"><metahttp-equiv="content-script-type"content="text/javascript"><metahttp-equiv="content-style-type"content="text/css"><title>ラングトンの蟻</title><styletype="text/css">#canvas{border:1pxsolid#999;width:300px;height:300px;}#canvasdiv{width:3px;height:3px;float:left;}</style><script>varearth=[];varWORLD_SIZE=100;varlang_ant;functionAnt(){}Ant.prototype={age:0,ageDisplay:undefined,id:undefined,speed:200,direction:[0,-1],//向き。x軸y軸。最初は上に動くposition:[60,40],//初期位置world:[],start:function(){varself=this;this.id=setInterval(function(){self.move()},1000/this.speed);},move:function(){this.ageDisplay.innerHTML=++this.age;this.moveNextCell();varcell=this.getCellInfo();varcolor=cell.getAndToggleColor();this.setNextDirection(color);},moveNextCell:function(){this.position[0]+=this.direction[0];this.position[1]+=this.direction[1];if(this.position[0]<0||this.position[1]<0||this.position[0]>=WORLD_SIZE||this.position[1]>=WORLD_SIZE){clearInterval(this.id);this.die();}},getCellInfo:function(){varidx=this.position[0]+this.position[1]*WORLD_SIZE;returnthis.world[idx];},setNextDirection:function(bool){//colorがfalse(白)なら右へ、true(黒)なら左へ転回if(bool){//黒vartmp=this.direction[0];this.direction[0]=this.direction[1];this.direction[1]=-tmp;}else{//白vartmp=this.direction[0];this.direction[0]=-this.direction[1];this.direction[1]=tmp;}},die:function(){alert('Langton\'s ant is dead.');throwtrue;}};functionCell(elm){this.elm=elm;}Cell.prototype={elm:undefined,color:false,//colorは2値なのでbooleanで表すcolorList:['#FFF','#000'],getAndToggleColor:function(){this.color=!this.color;vari=this.color?1:0;this.elm.style.backgroundColor=this.colorList[i];return!this.color;}}window.onload=function(){varcanvas=document.getElementById('canvas');vardiv='<div></div>';varinner_canvas="";for(vari=0;i<WORLD_SIZE*WORLD_SIZE;i++){inner_canvas+=div;}canvas.innerHTML=inner_canvas;varcells=canvas.childNodes;for(vari=0;i<cells.length;i++){//世界の誕生earth[i]=newCell(cells[i]);}lang_ant=newAnt();//蟻の誕生lang_ant.world=earth;//地球に降り立つlang_ant.ageDisplay=document.getElementById('step');document.getElementById('run').disabled=false;}</script></head><body><p><inputtype="button"value="run"onclick="lang_ant.start();this.disabled=true;"id="run"disabled="disabled"><spanid="step"></span><inputtype="button"value="stop & refresh"onclick="location.reload();"></p><divid="canvas"></div>
Songmu #9331() [ JavaScript ] Rating8/10=0.80
- 黒いマスにアリがいた場合、90°右に方向転換し、そのマスの色を反転させ、1マス前進する。
- 白いマスにアリがいた場合、90°左に方向転換し、そのマスの色を反転させ、1マス前進する。
詳しくはWikipedia等で調べるか、参考ページに拙作のデモがありますのでご覧下さい。
see: JavaScriptでラングトンの蟻
Rating8/10=0.80-0+
[ reply ]