2012-07-03 48 views
0

我目前使用一對布爾數組(水平和垂直)創建一個迷宮,以繪製迷宮線。Canvas OnDraw方法

迷宮中每一次只顯示數組中的5個布爾值。然後,我有一個始終居中的用戶,當他在迷宮中移動時,下一組佈景被繪製出來。這是正常的。

我遇到的問題是:當用戶移動到迷宮的某個部分時,for循環繪製的線條變得比bool數組更高,因此崩潰了應用程序。請在下面找到一些代碼片段。

的onDraw有:

protected void onDraw(Canvas canvas) { 
    canvas.drawRect(0, 0, width, height, background); 
    int currentX = maze.getCurrentX(),currentY = maze.getCurrentY(); 
    int drawSizeX = 6 + currentX; 
    int drawSizeY = 6 + currentY; 
    currentX = currentX - 2; 
    currentY = currentY - 2; 

    for(int i = 0; i < drawSizeX - 1; i++) { 
     for(int j = 0; j < drawSizeY - 1; j++) { 
      float x = j * totalCellWidth; 
      float y = i * totalCellHeight; 
      if(vLines[i + currentY][j + currentX]) { 
       canvas.drawLine(x + cellWidth, //start X 
           y,    //start Y 
           x + cellWidth, //stop X 
           y + cellHeight, //stop Y 
           line); 
      } 
      if(hLines[i + currentY][j + currentX]) { 
       canvas.drawLine(x,    //startX 
           y + cellHeight, //startY 
           x + cellWidth, //stopX 
           y + cellHeight, //stopY 
           line); 
      } 
     } 
     //draw the user ball 
     canvas.drawCircle((2 * totalCellWidth)+(cellWidth/2), //x of center 
          (2 * totalCellHeight)+(cellWidth/2), //y of center 
          (cellWidth*0.45f),     //radius 
          ball); 
    } 

編輯1 - 移動 -

public boolean move(int direction) { 
    boolean moved = false; 
    if(direction == UP) { 
     if(currentY != 0 && !horizontalLines[currentY-1][currentX]) { 
      currentY--; 
      moved = true; 
     } 
    } 
    if(direction == DOWN) { 
     if(currentY != sizeY-1 && !horizontalLines[currentY][currentX]) { 
      currentY++; 
      moved = true; 
     } 
    } 
    if(direction == RIGHT) { 
     if(currentX != sizeX-1 && !verticalLines[currentY][currentX]) { 
      currentX++; 
      moved = true; 
     } 
    } 
    if(direction == LEFT) { 
     if(currentX != 0 && !verticalLines[currentY][currentX-1]) { 
      currentX--; 
      moved = true; 
     } 
    } 
    if(moved) { 
     if(currentX == finalX && currentY == finalY) { 
      gameComplete = true; 
     } 
    } 
    return moved; 
} 

如果有別的,我需要澄清,請讓我知道。

在此先感謝。

+0

喂,是迷宮是Android類的一個實例還是你自己的?計算maze.getCurrentX()如何? maze.getCurrentY()?問候 – loloof64

+0

這是所有在單獨定義calss定義各種東西,如大小,最終位置等計算正如您可以在編輯的代碼中看到當前X和Y被定義爲0,然後根據用戶的移動增加和減少。 –

+0

在你的移動方法中,如果(currentY> 0 &&!horizo​​ntalLines [currentY-1] [currentX])爲什麼不編碼,用於向上方向測試。因此使用'>'運算符而不是'!='運算符。這樣你將會使用更多的防禦性編程。也許它不會解決你的問題,但它已經可以解決潛在的未來問題。 – loloof64

回答

1

drawSizeX/Y陣列之上索引時currentX/Y足夠高(長度-6)

所以限制值Math.min(電流+ 6,array.length)

+0

我沒有確切地知道我應該在哪裏使用這個,我之前已經在for循環中嘗試了一條if語句來將drawSize X/Y限制爲10和11.這確實阻止了應用程序崩潰,但是也阻止了用戶移動超過某一點,在這種情況下,不能移動到右邊的第六個街區。謝謝 –

+0

@LandLPartners我認爲你應該發佈更多的代碼,否則你的讀者可能會有困難來幫助你。 – loloof64

+0

@LaurentBERNABE我已經在我的問題中添加了另一段代碼,它們是迷宮類中的導入位和bool數組片段的附加部分。謝謝 –

相關問題