【发布时间】:2018-02-19 21:40:52
【问题描述】:
我一直在编写一个模拟 Langton's Ant 的处理脚本,但是我遇到了一个问题,它只会沿对角线移动。我一直在尝试修复它一段时间,但我无法弄清楚是什么导致了这个问题。我怀疑这可能与 turn() 函数有关。
代码如下:
int[][] grid;
int row;
int col;
int dir = 0;
final int DIR_UP = 0;
final int DIR_RIGHT = 1;
final int DIR_DOWN = 2;
final int DIR_LEFT = 3;
void setup()
{
size(500, 500);
background(255);
grid = new int[width][height];
col = width / 2;
row = height / 2;
}
void draw()
{
go();
}
void go()
{
int pix = col + row * width;
int state = grid[row][col];
loadPixels();
if(state == 0)
{
turn(1);
grid[row][col] = 1;
pixels[pix] = color(255);
}
else
{
turn(-1);
grid[row][col] = 0;
pixels[pix] = color(0);
}
updatePixels();
move();
}
void turn(int rotation)
{
dir += rotation;
if(dir < 0)
{
dir = 3;
}
else if(dir > 3)
{
dir = 0;
}
// Does not work, can return negative values
//dir = (dir + rotation) % 4;
}
void move()
{
switch(dir)
{
case DIR_UP:
row--;
case DIR_RIGHT:
col++;
case DIR_LEFT:
col--;
case DIR_DOWN:
row++;
}
if(col < 0)
col = width - 1;
else if(col >= width)
col = 0;
if(row < 0)
row = height - 1;
else if(row >= height)
row = 0;
}
【问题讨论】:
-
请不要将解决方案添加到您的问题中。如果您找到了最适合您的解决方案,那么您可以在下面接受它或回答您自己的问题。本网站鼓励其他用户提供多种解决方案,因为最适合您的解决方案可能不适用于其他用户。您的问题已回滚到之前的状态。欲了解更多信息,请访问help center。
标签: java grid processing cell simulation