Moving a Turtle

[Total: 0    Average: 0/5]

Remember the old drawing langauge GO? This will draw like that.

Head Code:

<script>
/* constants */
var LEFT=0;
var RIGHT=1;
var UP=2;
var DOWN=3;

function GRID_CONSTRUCT(_H,_W)
{
  this.HEIGHT=_H;
  this.WIDTH=_W;
  this.DIRECTION=DOWN;
  this.DRAWING=true;
  this.FLOOR;
  this.TURTLE_X;
  this.TURTLE_Y;
  this.PEN=function(_dir){this.DRAWING=(_dir==DOWN);}
  this.INIT=function()
  {
    this.FLOOR=new Array(this.HEIGHT);
    for(var i=0;i<this.HEIGHT;i++)
    {
      this.FLOOR[i]=new Array();
      for(var j=0;j<this.WIDTH;j++)
        this.FLOOR[i][j]=" ";
    }
  }
  this.INIT_TURTLE=function(x,y){this.TURTLE_X=x;this.TURTLE_Y=y;}
  this.MOVE=function(_l)
  {
    var x,y;
    if(this.DIRECTION==UP)   {y=-1;x=0;}
    if(this.DIRECTION==DOWN) {y=+1;x=0;}
    if(this.DIRECTION==LEFT) {y=0;x=-1;}
    if(this.DIRECTION==RIGHT){y=0;x=+1;}
    for(var i=0;i<_l;i++)
    {
      var a=this.TURTLE_X+x;
      var b=this.TURTLE_Y+y;
      if(a<this.WIDTH && a>=0 && b<this.HEIGHT && b>=0) /* move valid ? */
      {
        if(this.DRAWING){this.FLOOR[this.TURTLE_Y][this.TURTLE_X]="+";}
        this.TURTLE_X=a;this.TURTLE_Y=b;
      }
      else
      {
        alert("ERROR: You have moved the turtle off the known world.");
      }
    }
  }
  this.TURN=function(_d)
  {
    if(_d==LEFT)
    {
      if(this.DIRECTION==UP)this.DIRECTION=LEFT;
      else if(this.DIRECTION==LEFT)this.DIRECTION=DOWN;
      else if(this.DIRECTION==DOWN)this.DIRECTION=RIGHT;
      else if(this.DIRECTION==RIGHT)this.DIRECTION=UP;
    }
    else /* must be right */
    {
      if(this.DIRECTION==UP)this.DIRECTION=RIGHT;
      else if(this.DIRECTION==RIGHT)this.DIRECTION=DOWN;
      else if(this.DIRECTION==DOWN)this.DIRECTION=LEFT;
      else if(this.DIRECTION==LEFT)this.DIRECTION=UP;
    }
  }
  this.PRINT=function()
  {
    var s="";
    for(var i=0;i<this.HEIGHT;i++)
    {
      for(var j=0;j<this.WIDTH;j++)
      {
        if(this.TURTLE_X==j && this.TURTLE_Y==i)
        {
          s+="*";
        }
        else
        {
          s+=this.FLOOR[i][j];
        }
      }
      s+="n";
    }
    //alert(s);
    document.f1.t1.value=s;
  }
}
function goNow()
{
var GRID=new GRID_CONSTRUCT(20,20);
GRID.INIT();
GRID.INIT_TURTLE(0,0);
GRID.PEN(DOWN);
GRID.MOVE(5);
GRID.TURN(LEFT);
GRID.MOVE(5);
GRID.TURN(LEFT);
GRID.MOVE(5);
GRID.TURN(LEFT);
GRID.MOVE(5);
GRID.PRINT();
}
</script>

Body Code:

<form name="f1">
<table align=center><tr><td>
<textarea name="t1" rows=20 cols=20></textarea>
</td></tr></table>
</form>
<script>goNow()</script>

Times Viewed: 9

Leave a Reply

Your email address will not be published. Required fields are marked *