引用索引数组

时间:2012-10-09 00:16:41

标签: java arrays slick2d

  

可能重复:
  Checking against indexed arrays

所以我有我的代码,每次按下鼠标时,它会在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;
    }

}

2 个答案:

答案 0 :(得分:2)

您可以将坐标用作哈希并将点存储在HashSet中,只需使用x * y

之类的东西重载Point的哈希函数

答案 1 :(得分:0)

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

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方法中测试它来获得更好的服务,以避免在重复时将点添加到数组中。

祝你好运!