RosettaCodeData/Task/Langtons-ant/Scilab/langtons-ant.scilab
2023-07-01 13:44:08 -04:00

71 lines
2.8 KiB
Text

grid_size=100; //side length of the square grid
ant_pos=round([grid_size/2 grid_size/2]); //ant's initial position at center of grid
head_direction='W'; //ant's initial direction can be either
//'N' north, 'S' south, 'E' east, or 'W' west
grid=~zeros(grid_size,grid_size) //blank grid
col=[]; //cell color handler
next_step=%T; //step flag
i=0; //step counter
while next_step
col=grid(ant_pos(1),ant_pos(2)); //get cell color
if col then //if white cell
grid(ant_pos(1),ant_pos(2))=~grid(ant_pos(1),ant_pos(2)); //switch color
if head_direction=='N' then //if head to N
head_direction='E'; //turn right to E
ant_pos(2)=ant_pos(2)+1; //step forward
elseif head_direction=='E' then //if head to E
head_direction='S'; //turn right to S
ant_pos(1)=ant_pos(1)+1; //step forward
elseif head_direction=='S' then //if head to S
head_direction='W'; //turn right to W
ant_pos(2)=ant_pos(2)-1; //step forward
elseif head_direction=='W' then //if head to W
head_direction='N'; //turn right to N
ant_pos(1)=ant_pos(1)-1; //step forward
end
else //if black cell
grid(ant_pos(1),ant_pos(2))=~grid(ant_pos(1),ant_pos(2)); //switch color
if head_direction=='N' then //if head to N
head_direction='W'; //turn left to E
ant_pos(2)=ant_pos(2)-1; //step foward
elseif head_direction=='W' then //if head to W
head_direction='S'; //turn left to S
ant_pos(1)=ant_pos(1)+1; //step forward
elseif head_direction=='S' then //if head to S
head_direction='E'; //turn left to E
ant_pos(2)=ant_pos(2)+1; //step forward
elseif head_direction=='E' then //if head to E
head_direction='N'; //turn left to N
ant_pos(1)=ant_pos(1)-1; //step forward
end
end
i=i+1;
if ant_pos(1)<1 | ant_pos(1)>100 | ant_pos(2)<0 | ant_pos(2)>100 then //check ant's position
disp("Out of bounds after "+string(i)+" steps");
next_step=~next_step; //break loop if out of bounds
end
end
ascii_grid=string(zeros(grid)); //create grid of chars to display
//on the console
for a=1:length(grid)
if grid(a) then
ascii_grid(a)=" "; //blank space if cell is white
else
ascii_grid(a)="#"; //# if cell is black
end
end
disp(ascii_grid);