JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var cells=[];
var rules=[];
var cellSize=10;
var colors=['black', 'white', '#ff0000', '#ff7f00', '#ffff00', '#00ff00', '#0000ff', '#4b0082', '#8b00ff'];
var rotation=[
{x:0,y:1},
{x:1,y:0},
{x:0,y:-1},
{x:-1,y:0}
];
var frame=0, keepOnAnim=true, steps=0;
function Ant(ww, hh, rules, x, y, zoom){
if(end.className==='visible') end.classList.remove('visible')
initCells(ww, hh, zoom);
setRules(rules);
this.x=x;
this.y=y;
this.direction=rotation[0];
this.dirIndex=0;
this.killed=false;
}
Ant.prototype.changeDir=function(num){
this.dirIndex+=num;
if(this.dirIndex<0) this.dirIndex=rotation.length-1;
if(this.dirIndex===rotation.length) this.dirIndex=0;
this.direction=rotation[this.dirIndex];
}
Ant.prototype.step=function(){
this.x+=this.direction.x;
this.y+=this.direction.y;
var x=this.x, y=this.y;
if(cells.length>y&&cells.length>x){
var rule=rules[cells[y][x]];
switch(rule){
case 'l':this.changeDir(1); break;
case 'r':this.changeDir(-1); break;
}
cells[y][x]+=1;
cells[y][x]%=rules.length;
drawCell(this.x, this.y, cells[y][x]);
a.width+=0;
var aCtx=a.getContext('2d');
aCtx.fillStyle='rgba(0, 0, 0, 0.5)';
aCtx.fillRect(this.x*cellSize, this.y*cellSize, cellSize, cellSize);
}else{
if(!this.killed){
keepOnAnim=false;
end.classList.add('visible');
this.killed=true;
}
}
}
function drawCell(x, y, index){
ctx.fillStyle=colors[index%colors.length];
ctx.fillRect(x*cellSize, y*cellSize, cellSize, cellSize);
}
function initCells(ww, hh, zoom){
c.width=ww*zoom;
c.height=hh*zoom;
a.width=ww*zoom;
a.height=hh*zoom;
cellSize=zoom;
ctx=c.getContext('2d');
cells=[];
for(var i=0; i
cells.push([]);
for(var j=0; j
cells[i].push(0);
}
}
}
function setRules(card){
rules=card;
}
/* l as in left
* o as in over (don't turn)
* r as in right
*/
function anim(){
if(keepOnAnim) window.requestAnimationFrame(anim);
frame+=ctrl.speed;
for(var step=0; step
ant.step();
frame-=1;
++step;
}
}
function Ctrl(){
this.speed=1;
this.rules='rlolr';
this.width=100;
this.height=100;
this.pixelSize=6;
this.startX=20;
this.startY=20;
this.step=function(){ant.step()};
this.genAnt=function(){
ant=new Ant(this.width, this.height, this.rules, this.startX, this.startY, this.pixelSize);
steps=0;
frame=0;
if(!keepOnAnim){
keepOnAnim=true;
anim();
}
};
this.togglePause=function(){
keepOnAnim=!keepOnAnim
anim();
}
}
var ctrl=new Ctrl;
var gui=new dat.GUI;
gui.add(ctrl, 'speed', 0, 1000);
gui.add(ctrl, 'rules');
gui.add(ctrl, 'width');
gui.add(ctrl, 'height');
gui.add(ctrl, 'pixelSize');
gui.add(ctrl, 'startX');
gui.add(ctrl, 'startY');
gui.add(ctrl, 'genAnt');
gui.add(ctrl, 'togglePause');
var ant;
ctrl.genAnt();
anim();