-1

我从板的底部开始向上搜索行。如果它找到一个占用的插槽,则假设将对象继续向下放置 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);
    }
}
4

1 回答 1

0

您的代码中有两个问题:

  1. 由于每个操作涵盖两行,因此您需要迭代的行数比总行数少。如果访问 15+1 会导致 OOB 异常,因为数组只有 16 行并且计数从 0 开始。
  2. 除了两个 for 循环之外,您不需要 while 循环。外循环的下一次迭代将处理上面的块。

修复(假设 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();
}

pscol并且row可能是循环计数器的更好名称。

于 2013-07-07T03:22:00.580 回答