有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

搜索二维数组的java算法

我正试图重现一个类似俄罗斯方块的游戏。我有一个2D数组,“_tiles”存储名为“ColorShape”的对象

private ColorShape[][] _tiles = new ColorShape[8][17];; 

当我点击向下箭头键找到阵列中的下一个可用插槽以快速放置形状时,我正在尝试创建一个quickDrop()方法。我很难想出一种算法,可以在该片段所在的列中搜索当前片段下方的行

到目前为止,我一直在尝试这样做,但我认为我完全错了:(这些块是30x30像素,这就是为什么它们被30除,所以阵列位置对应于形状的x和y位置)

public void quickDrop(){

   // j is the column that the piece is currently in
   int j = _proxyPiece.getXLocation()/30;

    for (int i=0; i<17;i++){

        if(_tiles[j][i] == null)
          continue;



       else if (_tiles[j][i] != null){
         _tiles[j][i-2] =  _proxyPiece.getFirstPiece();  
         _tiles[j][i-1] =  _proxyPiece.getSecondPiece();
         repaint();

         _proxyPiece.setPiece(this.newPiece());
         repaint();
         break;
       }    


  }
}

public void paintComponent(Graphics g) {
    if (_pauseState == false){
    _pauseText.setVisible(false);
    super.paintComponent(g);
    // simplify the positioning of things.
    g.translate(0, 0);

    //Draws the board outline and fills it white
    g.setColor(Color.WHITE);
    g.drawRect(0, 0, 240, 480);
    g.fillRect(0, 0, 240, 480);

    //Draws a dark gray grid 
    g.setColor(Color.DARK_GRAY);

        for(int x = 0; x < COL_COUNT + 1; x++) {
            for(int y = 0; y < VISIBLE_ROW_COUNT+1; y++) {
                g.drawLine(0, y * TILE_SIZE, COL_COUNT * TILE_SIZE, y * TILE_SIZE);
                g.drawLine(x * TILE_SIZE, 0, x * TILE_SIZE, VISIBLE_ROW_COUNT *    TILE_SIZE);
            }
        }

    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);
        }
    }
}
   else if (_pauseState == true){
       _pauseText.setVisible(true);
       super.paintComponent(g);
       // simplify the positioning of things.
       g.translate(0, 0);
       g.setColor(Color.WHITE);
       g.drawRect(0, 0, 240, 480);
       g.fillRect(0, 0, 240, 480);

    }

}

共 (1) 个答案

  1. # 1 楼答案

    解决这个问题的一个算法是:

    1. 取下当前下落件,将其从当前位置向下移动到每个Y值上
    2. 如果它与之前放置的工件碰撞,或超出网格底部,则您最后检查的Y位置是有效的解决方案

    如果您想要所有有效的解决方案,而不是只有一个,请对当前选定工件的所有可能旋转重复此算法

    下面是一个算法示例。它无法按原样处理您的代码,但它会让您快速开始

    ColorShape[][] grid = new ColorShape[width][height];
    TetrisShape shape = new TetrisShape(Shape.L_SHAPE);
    
    //position will be bottom left coordinate of bounding rectangle of dropping shape.
    Point position = new Point(shape.getPosition());
    int resultY = -1;
    for(int dy=0;dy<height;dy++){
        for(int y=0;y<height;y++){
            int shapeY = position.y+y;
            if(shapeY>=height || shape.intersectsGrid(grid)){
                resultY = shapeY -1;
                break;
            }        
        }
    }