为类似俄罗斯方块的游戏压缩2D数组的算法

时间:2013-07-07 03:09:42

标签: java sorting multidimensional-array

我从电路板底部开始向上搜索行。如果找到占用的插槽,则假设将对象保持在1个插槽中,直到它碰到电路板的底部。然而,它没有这样做,

我希望我的循环用对象设置自由位置,然后清除对象所在的位置。在将新的颜色形状添加到数组后调用此方法(有时会删除_tiles中的碎片并使它们浮动在半空中)

//ColorShape is an abstract class that can either be a java.awt.geom.Ellipse2D.Double or java.awt.geom.Rectangle2D.Double
private static ColorShape[][] _tiles = new ColorShape[8][16]; 


public void condenceTiles(){
    ColorShape _colorShape;   
    for (int i = 15; i > 0; i--){
        for(int j = 0; j < 8; j++){
            if(_tiles[j][i] == null && _tiles[j][i-1] != null) {
                //System.out.println("im condencing");
                _colorShape = _tiles[j][i-1];

                _tiles[j][i] = _colorShape;
                _tiles[j][i-1] = null;
                repaint();
            }
        }
    }
    repaint();
}

public void paintComponent(Graphics g) {
    Graphics2D aBetterPen = (Graphics2D)g;    
    _proxyPiece.fill(aBetterPen);

    for (int i = 0; i<16; i++){
        for(int j=0; j<8;j++){
            if(_tiles[j][i] != null)
                _tiles[j][i].fill(aBetterPen);
        }
    }
}

import java.awt.Color;
import java.awt.geom.*;
import java.awt.*;
public abstract class ColorShape
{
    private RectangularShape _shape; //component
    private Color _borderColor, _fillColor;
    private double _rotation;
    private final int STROKE_WIDTH = 2;
    private boolean _isCounted;
    private int _type; //1 is rectangle, 2 is circle

    // removed a lot of methods/constructor so I can show draw and fill methods 

    public void draw (java.awt.Graphics2D aBrush){
        Color savedColor = aBrush.getColor();
        aBrush.setColor(_borderColor);
        Stroke savedStroke = aBrush.getStroke();
        aBrush.setStroke(new BasicStroke(STROKE_WIDTH));
        aBrush.rotate(_rotation, _shape.getCenterX(), _shape.getCenterY());
        aBrush.draw(_shape);
        aBrush.rotate(-_rotation, _shape.getCenterX(), _shape.getCenterY());
        aBrush.setStroke(savedStroke);
        aBrush.setColor(savedColor);
    }
    public void fill (Graphics2D aBrush){
        Color savedColor = aBrush.getColor();
        aBrush.setColor(_fillColor);
        aBrush.rotate(_rotation, _shape.getCenterX(), _shape.getCenterY());
        aBrush.fill(_shape);
        aBrush.rotate(-_rotation,_shape.getCenterX(),_shape.getCenterY());
        aBrush.setColor(savedColor);
    }
}

1 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题:

  1. 由于每个操作都包含两行,因此您需要比总计少一行迭代。如果您访问将导致OOB异常的15 + 1,因为该数组只有16行并且计数从0开始。
  2. 除了两个for循环之外,您不需要while循环。外循环的下一次迭代将处理上面的块。
  3. 修复(假设15是底部,0是顶部):

    public void condenceTiles(){
      for (int i = 15; i > 0; i--){
        for(int j = 0; j < 8; j++){
          if(_tiles[j][i] == null && _tiles[j][i-1] != null) {
            _tiles[j][i] = _tiles[j][i-1];
            _tiles[j][i-1] = null;
          }
        }
      }
      repaint();
    }
    

    P.S。 colrow可能是循环计数器的更好名称。