一个接一个地设置位置,直到整个盒子被填满

时间:2014-01-11 08:41:02

标签: java

所以我需要更新我的对象的位置,在这种情况下只是1x1像素的正方形。我需要将它的位置设置在地图的顶部,这只是一个更大的正方形然后更改X直到它达到50,这是地图的大小。然后它需要将Y改变为1,然后它向右移动,X转为1,然后Y再次改变1,再转向左等,依此类推。

我需要这样做:

这是一个小例子:

You are the cross.
|=========|
|         |
|    +    |        
|         |
|=========|

Then i need to do this:
|=========|
|+----->\/|
|\/<------|        
|------->+|
|=========|

我目前的代码是:

String split[] = s.split(" ");
radiusX = Integer.parseInt(split[1]);
radiusZ = radiusX;
int valX = 0;
int valY = 0;
while(valX <= radiusX && valY <= radiusY) {
      valX = valX + 1;
      valY = valY + 1;
}

但是现在只需将玩家发送到地图的角落。

2 个答案:

答案 0 :(得分:0)

你正在做的是通过同时添加到X和Y来对角行走。如果你想进行某种螺旋运动,你需要两个循环,一个用于改变X值,一个内圈用于Y值。

答案 1 :(得分:0)

尝试使用此代码,它会让您对需要完成的工作有所了解。

基本上你需要一个当前位置(x,y)和一个增量矢量 通过更改增量矢量,您可以告诉您的交叉点/下一步的位置。

这段代码可以概括,并且更加简洁,但是可以 可能会让它更加神秘,也不会说明主要观点。

/**
 * Represents a radius-vector in 2D. 
 * Also it is reused for representing a 2D
 * point (through its radius-vector).
 */
class Vector {
    public int x;
    public int y;

    public Vector(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

public class Test033 {

    public static void main(String[] args) {

        // x is the column index
        // y is the row index

        int x;
        int y;

        // these define the sizes of the grid
        int x_min = 1;
        int x_max = 4;
        int y_min = 1;
        int y_max = 6;

        // we start from this point
        x = x_min;
        y = y_min;

        Vector pos = new Vector(x, y); // represents the position (x,y)
        Vector inc = new Vector(1, 0); // represents the increment (on both x and y)

        boolean start = true;
        int cnt = x_max * y_max;
        int k = 0;

        while (true) {

            System.out.println(String.format("x/col = %d y/row = %d", pos.x, pos.y));

            if (!start && inc.x == 1 && pos.x == x_max) {
                inc.x = -1;
                inc.y = 0;
                pos.y += 1; // y position
            } else if (!start && inc.x == -1 && pos.x == x_min) {
                inc.x = 1;
                inc.y = 0;
                pos.y += 1; // y position
            } else {
                pos.x += inc.x;
                pos.y += inc.y;
            }

            start = false;
            k++;
            if (k >= cnt){
                break;
            }
        }

    }

}