gpt4 book ai didi

java - Canvas OnDraw方法

转载 作者:行者123 更新时间:2023-12-01 15:18:28 25 4
gpt4 key购买 nike

我目前正在使用一对 boolean 数组(水平和垂直)创建一个迷宫,以便为迷宫绘制线条。

迷宫一次仅显示数组中的 5 个 boolean 值。然后,我有一个始终处于中心位置的用户,当他穿过迷宫时,会绘制下一组 boolean 值。这正在正常工作。

我遇到的问题是:当用户移动到迷宫的某个部分时,绘制线条的 for 循环变得高于 bool 数组,因此导致应用程序崩溃。请在下面找到一些代码 fragment 。

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;
}

如果还有什么需要我澄清的,请告诉我。

提前致谢。

最佳答案

当 currentX/Y 足够高(长度为 6)时,drawSizeX/Y 在数组上建立索引

因此将值限制为 Math.min(current + 6, array.length)

关于java - Canvas OnDraw方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com