java - 均匀地在一条线上展开对象

时间:2010-12-02 19:28:54

标签: java object line

我在由这段代码创建的窗口中的一行上创建对象:

void createTurtles() {
     int nrTurtles = Keyboard.nextInt("Set amount of turtles: ");
     w = new GraphicsWindow(500, 300);
     drawLinez();
     for (int k = 1; k <= nrTurtles; k++) {
        Turtle t = new Turtle(w, 50, 50 + k*10);
        t.right(90);
        t.setSpeed(100);
        t.penDown();
        turtles.add(t);
     }
}

此代码行:

        Turtle t = new Turtle(w, 50, 50 + k*10);

当时创造一只乌龟。现在我已经设定了海龟的Y坐标为50,X协调为50 + k * 10。这是因为该行从X坐标50开始,停在X坐标250处。

现在我想要的是,根据创建的乌龟nr(用户输入这个),我希望乌龟在这条线上均匀分布。怎么做?它与我写的行有关,可能是k值或10。

图片中显示了这条线(见下面的链接),它是红线,表示创建了海龟的数量。

1 个答案:

答案 0 :(得分:3)

将窗口的height - 100与海龟的数量相对应,您将获得distanceBetweenTurles

int nrTurtles = Keyboard.nextInt("Set amount of turtles: ");

int height = 300;
w = new GraphicsWindow(500, height);

drawLinez();

double distanceBetweenTurles = (height - 100.0) / nrTurtles;

for (int k = 1; k <= nrTurtles; k++) {
    Turtle t = new Turtle(w, 50, 50 + (int) (k * distanceBetweenTurtles));
    t.right(90);
    t.setSpeed(100);
    t.penDown();
    turtles.add(t);
}