带网格的2D阵列

时间:2012-04-02 21:11:36

标签: java turtle-graphics

我创建了一个使用乌龟图形绘制不同形状的程序。底部有一个离散的网格,5x5,位于400px到400px的JFrame之上。它包裹着顶部/底部和左/右,以防形状结束。

我现在需要做的是添加一个2d数组,创建一个400x400的0s数组。如果乌龟移动通过任何像素(对应于2d阵列中的一个点),则需要将0更改为1.什么是最好的方法?我们最终正在努力实现康威生命游戏的功能。

1 个答案:

答案 0 :(得分:0)

在我看来,最好的方法是跟踪龟的位置(X& Y),用double变量指示方向,然后用基本三角法计算下一个'像素'那个tutrtle击中了。我假设您将使用计时器或循环运行此代码,因此它看起来像这样:

//This code is somehwere in your program
class Turtle
{
     private double x;
     private double y;
     private double direction; //direction in radians
    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public double getY() {
        return y;
    }
    public void setY(double y) {
        this.y = y;
    }
    public double getDirection() {
        return direction;
    }
    public void setDirection(double direction) {
        while(direction > Math.PI * 2)
        {
            direction -= Math.PI * 2;
        }
        while(direction < 0)
        {
            direction += Math.PI * 2;
        }
        this.direction = direction;
    }
}

private static final int GRID_WIDTH = 400;
private static final int GRID_HEIGHT = 400;


private Turtle myTurtle = new Turtle();
private boolean[][] grid = new boolean[GRID_WIDTH][GRID_HEIGHT];
JFrame myJFrame = new JFrame();
private Graphics gridImage = myJFrame.getGraphics();

private void initialise()
{
    for(int y = 0; y < GRID_HEIGHT; y++)
    {
        for(int x = 0; x < GRID_WIDTH; x++)
        {
            grid[x][y] = false;
        }
    }

    gridImage.setColor(Color.BLACK);
    gridImage.fillRect(0, 0, GRID_WIDTH, GRID_HEIGHT);
    gridImage.setColor(Color.white);
}

//This code would be inside the loop or timer callback function
private void myMainFunction()
{
    double newX, newY;
    double deltaX, deltaY;

    deltaX = Math.cos(myTurtle.getDirection());
    deltaY = Math.sin(myTurtle.getDirection());

    newX = myTurtle.getX() + deltaX;
    newY = myTurtle.getY() + deltaY;

    if(newX < 0)
    {
        newX += GRID_WIDTH; 
    }
    else if(newX > GRID_WIDTH)
    {
        newX -=  GRID_WIDTH;    
    }

    if(newY < 0)
    {
        newY += GRID_HEIGHT; 
    }
    else if(newY > GRID_HEIGHT)
    {
        newY -=  GRID_HEIGHT;   
    }

    grid[(int)Math.floor(newX)][(int)Math.floor(newY)] = true;

    gridImage.fillRect((int)Math.floor(newX), (int)Math.floor(newY), 1, 1);
    myJFrame.update(gridImage);

    myTurtle.setX(newX);
    myTurtle.setY(newY);
}