我目前使用一對布爾數組(水平和垂直)創建一個迷宮,以繪製迷宮線。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;
}
如果有別的,我需要澄清,請讓我知道。
在此先感謝。
喂,是迷宮是Android類的一個實例還是你自己的?計算maze.getCurrentX()如何? maze.getCurrentY()?問候 – loloof64
這是所有在單獨定義calss定義各種東西,如大小,最終位置等計算正如您可以在編輯的代碼中看到當前X和Y被定義爲0,然後根據用戶的移動增加和減少。 –
在你的移動方法中,如果(currentY> 0 &&!horizontalLines [currentY-1] [currentX])爲什麼不編碼,用於向上方向測試。因此使用'>'運算符而不是'!='運算符。這樣你將會使用更多的防禦性編程。也許它不會解決你的問題,但它已經可以解決潛在的未來問題。 – loloof64