Delphi, 244
var g:string;a:PChar;i,d:Int32;begin d:=0;g:=StringOfChar('_',289);a:=@g[144];Read(i);repeat d:=d-1+2*Ord(a^='_');a^:=Chr(Ord(a^)xor$7C);a:=a+(1-1*(d and 2))*(1+16*(d and 1));i:=i-1;until i<0;a^:='@';for i:=0to 16do WriteLn(Copy(g,i*17,17))end. NOTE : Somehow my code gives other output than the above mentioned example, but I can't tell if it's an error on my side or in the example. Please read my code and comment on this...
The indented & commented code reads like this :
var g:string; a:PChar; i,d:Int32; begin d:=0;// d: Ant start 'd'irection faces right (=0, see below) g:=StringOfChar('_',289);// g: The grid is initially completely white. (size=17*17=289) a:=@g[144]; // a: Ant position starts at the center of the grid (=8*17+8) Read(i); repeat // Turn 90° right if at an '_' space), 90° left otherwise; // This works by always subtracting 1, but adding 2 if we're at a '_' : d:=d-1+2*Ord(a^='_'); // Flip the color of the square; // This is done via an xor with the appropriate value : a^:=Chr(Ord(a^)xor$7C);// 95>35>95 // Move one unit forward; // For this, determine the step size, using the two least significant bits of d. // This gives the following relation : // 00 = 90° = right = 1 // 01 = 180° = down = 17 // 10 = 270° = left = - 1 // 11 = 0° = up = -17 // (d and 2) gives 0 or 2, translate that to 1 or -1 // (d and 1) gives 0 or 1, translate that to 1 or 17 // Multiply the two to get an offset 1, 17, -1 or -17 : a:=a+(1-1*(d and 2))*(1+16*(d and 1)); i:=i-1; until i<0; // Place the and and print the grid : a^:='@'; for i:=0to 16do WriteLn(Copy(g,i*17,17)) end. Input:
450 Output :
_________________ _________________ ___________##____ ____##______##___ ___#__#@___##_#__ __###_###__#__#__ __#_#_#_#__#_#___ _____###___#_____ _____#___________ _____#__###______ ___#_#_#__#_#_#__ __#__#_#____###__ __#_##__##___#___ ___##______##____ ____##___________ _________________ _________________