2017-04-26 62 views
-1

我有一個2d字符數組,代表類似於俄羅斯方塊的遊戲板。如果連續排列三個或更多,我會從板上移除塊。現在,我想基本上刪除塊之間的空間。所以我想從右下角開始,然後走到每一列,然後移到下一列。當我達到一個空白'。'一塊,我需要把所有東西都轉移下來。我如何有效地將二維數組中的所有內容按給定的數量向下移動?

這裏有我想要使用

public void boardGravity() { 

     for (int j = c - 1; j > 0; j--) { 
      for (int i = r - 1; i > 0; i--) { 
       if (board[i][j] != '.') { 
        int count = 0; 
        while(isEmpty(i + count + 1, j)) { 
         count++; 
        } 
        board[i + count][c] = board[r][c]; 
        board[r][c] = '.'; 
       } 
      } 
     } 
    } 

    public boolean isEmpty(int row, int col) { 
     if (row >= 0 && col >= 0 && board[row][col] == '.') { 
      return true; 
     } 
     return false; 
    } 

我有一個很難包裝我的頭圍繞這一邏輯的方法!我找不到任何與此相似的東西。

編輯:下面是一個例子輸出:

New Board Created! 
..... 
..... 
..... 
..... 
..... 
..... 

..... 
..... 
..... 
a.... 
a.... 
a.... 

a.... 
c.... 
b.... 
a.... 
a.... 
a.... 

a.... 
c.... 
b.... 
..... 
..... 
..... 

a.... 
c.... 
b.... 
..... 
..... 
..... 

在最後的印刷電路板,我需要在頂部的剩餘字符要被移動至底部。

+0

你能舉一個板子的例子,你期望發生什麼,以及當你運行你的代碼時實際發生了什麼? – tucuxi

+0

[你的步調試器告訴你什麼?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –

+0

Sure !好的,我添加了經理的示例輸出。我需要像俄羅斯方塊一樣將遊戲片斷轉移。 – presence

回答

0

其實你並不需要檢測空行,它很容易做的:

public void boardGravity() { 
    for (int i = r - 1; i > 0; i--) 
     System.arraycopy(board[i - 1], 0, board[i], 0, c); 
    Arrays.fill(board[0], '.'); 
} 
0

您還沒有表現出足夠的代碼給出一個明確的答案(和我們不在這裏寫你代碼無論如何!),但我可以給你一個通用的解決方案。

您需要兩個指針,一個是「寫入」指針,一個是「讀取」指針。該指針最有可能只是一個整數值,用於指示將數組編入索引。

Start with both at 0. 

Loop until read pointer reaches top of column 
    Increment the read pointer 
    If you find a match 
     Copy the value to the write pointer 
     Increment the write pointer. 

Loop until write pointer reaches top of column 
    Increment the write pointer 
    Write a blank space 

你需要計算出你自己的代碼是什麼算作一場比賽 - 一個空的空間。如果你想限制讀指針和寫指針之間的差異(所以所有的東西都會拖垮最多X個空格),或者只是想將所有東西都移動到底部,你還需要弄清楚。

0

您可以將您的任務分解爲名稱清晰的方法,從而使您的任務更輕鬆。

void boardGravity(int[][] board) { 
     for(int column = 0; column < board.length; column++) { 
      columnGravity(board[column]); 
     } 
} 

void columnGravity(int[] column) { 
     for(int row = 0; row < column.length; column ++) { 
      if(isEmpty(column[row]) { 
       dropCells(column, row + 1); 
      } 
     } 
} 

...等等。

這假定你的「板」是一列數組,而你的列是底部爲0的單元格數組。但它可以適應。

如果您將數組隱藏在Board類中並使用適合抽象的方法名與其交互,那麼您的代碼將變得更容易理解。

相關問題