0

可能重复:
检查索引数组

所以我有我的代码,每次按下鼠标时,它都会在 mouseX 和 mouseY 处绘制一个新粒子并将位置存储在一个数组中,以便它可以更新直到它到达屏幕底部时被告知停止。我想做的是检查当前位置与已经“制造”的粒子的位置,如果它具有相同的坐标,则让它更快停止,以产生堆叠效果,有人可以帮我吗?

    import java.awt.Point;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class Control extends BasicGameState {
    public static final int ID = 1;

    public Methods m = new Methods();
    public Point[] point = new Point[(800 * 600)];

    int pressedX;
    int pressedY;
    int num = 0;
    String Build = "1.1";

    public void init(GameContainer container, StateBasedGame game) throws SlickException{
    }

    public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
        for (int index = 0; index < point.length; index++) {
            Point p = point[index];
            if (p != null) {
                if (p.y >= 598) {
                    m.drawParticle(point[index].x,(point[index].y));
                } else {
                    m.drawParticle(p.x, p.y);
                    p.y++;
                }
            }
        }
        g.drawString("Particle Test", 680, 0);
        g.drawString("Build: " + Build, 680, 15);
        g.drawString("Pixels: " + num, 10, 25);
    }

    public void update(GameContainer container, StateBasedGame game, int delta) {
    }

    public void mousePressed(int button, int x, int y) {
        pressedX = x;
        pressedY = y;
        num = num + 1;
        point[num] = new Point(pressedX, pressedY);
        }

    public int getID() {
        return ID;
    }

}
4

2 回答 2

2

您可以将坐标用作哈希并将点存储在 HashSet 中,只需用 x*y 之类的东西重载 Point 的哈希函数

于 2012-10-09T00:27:41.230 回答
0

您可以编写一个新方法来检查该点是否位于数组中小于“Index”的索引处。

public boolean isInArray(int index)
{
    for (int index2 = 0; index2 < index; index2++)
    {
        if( (point[index2].x == point[index].x) &&
            (point[index2].y == point[index].y) )
        {
            return true;    //point(index) is previously in array
        }
    }
    return false;    //point(index) is NOT previously in array
}

然后在你的 for..next 循环中,你需要使用 break 语句

if (isInArray(index))
{
    //the break statement causes the program to exit the current loop
    break;
}

但是,最好通过在 MousePressed 方法中对其进行测试来为您提供更好的服务,以避免首先将点添加到数组中(如果它是重复的)。

祝你好运!

于 2012-10-09T01:39:35.950 回答