2017-08-31 62 views
0

我对编码还很陌生,所以我只是试图制作一些简单的游戏,如Snake。现在我正试图让苹果吃掉时跟踪头部,但我遇到了问题。ArrayList中的动态矩形

我目前拥有它,以便在合适的时间在正确的地方产卵,但它们不会移动。他们产卵并变得静止。我的尾部件存储在一个ArrayList中,我不知道如何更新每个刻度的矩形的坐标值。如何修改每个矩形的每个矩形的坐标值?

这是我到目前为止。这里是滋生尾部件和油漆他们

public static ArrayList<Integer> xValues = new ArrayList(1); 
public static ArrayList<Integer> yValues = new ArrayList(1); 
public static ArrayList<Rectangle> tails = new ArrayList(1); 
public static int tail = 1; 

public static void paint(Graphics g) { 
    g.setColor(Color.green); 
    g.fillRect(sx, sy, sWidth, sHeight); 

    if(Apple.collision) { 
     tails.add(new Rectangle(xValues.get(xValues.size() - tail), 
     yValues.get(yValues.size() - tail), sWidth, sHeight)); 
     System.out.println(tails.size()); 
     Apple.collision = false; 
    } 

    for(int i = 0; i < tails.size(); i++) { 
     g.setColor(Color.green); 
     g.fillRect(tails.get(i).x, tails.get(i).y, tails.get(i).width, tails.get(i).height); 
    } 
} 

public static void update() { 
    sx += svx; 
    sy += svy; 

    xValues.add(sx); 
    yValues.add(sy); 
} 

我想要做的就是每场比赛蜱我想1.所以刚才尾++递增变量“尾巴”我的蛇类的一部分。当我吃苹果的时候,我在苹果课上做这个。

public static void update() { 
    if(Snake.sx == ax && Snake.sy == ay) { 
     ax = (int) ((20 - 0) * random()) * 20; 
     ay = (int) ((20 - 0) * random()) * 20; 
     Snake.tail++; 

     collision = true; 
    } 

但是,这个矩形不是动态的,所以它们不会增加每个勾号的尾部。

我知道我可以通过设置一个for循环找到的长方形的x值,并且有类似

tail.get(i).getBounds().getX; 

但我想不通的程序运行时,我可以怎样改变坐标值。

在此先感谢!

回答

0

为了保持tails矩形的更新,您必须在每个剔号处通过列表并将每个尾段的坐标设置为它前面的坐标,否则您必须添加一个新的矩形并且每剔掉一个最老的(如FIFO队列)。

但是,由于您已经存储了所有过去的x/y值,因此tails列表仅包含冗余信息。您可以完全放下它,只需读取最后一个x/y值的tail以获得每个尾部坐标。

public static void paint(Graphics g) { 
    g.setColor(Color.green); 
    g.fillRect(sx, sy, sWidth, sHeight); 

    if (Apple.collision) { 
//  tail++; // could do this here instead of in Apple.update 
     System.out.println(tail); 
     Apple.collision = false; 
    } 

    for (int i = 0; i < tail; i++) { 
     g.setColor(Color.green); 
     g.fillRect(xValues.get(xValues.size() - 1 - i), yValues.get(yValues.size() - 1 - i), sWidth, sHeight); 
    } 
} 
+0

太棒了,这让我对现在更有意义!我只是猜测和检查,但你做得这么简单。非常感谢你! – CoderKlipto