我有一个代表生物的结构方阵。每个生物都可以向左、向上、向右或向下移动。我正在检查空单元格的相邻矩阵位置,并对新坐标进行以下计算:
function res = Move2(worldDimension,row,col,left,up,right,down)
%In the following matrices, good moves are > 0.
%Directions pattern:
patternMatrix = [0 2 0;
1 5 3;
0 4 0];
%Possible border moves:
borderMatrix = [0 (row>1) 0;
(col>1) 1 (col<worldDimension);
0 (row<worldDimension) 0;];
%Possible neighbor moves:
neighborsMatrix = [0 (up==0) 0 ;
(left==0) 1 (right==0);
0 (down==0) 0;];
%Matrix of possible directions including neighbors and borders
possibleMovesMatrix = ((borderMatrix).*(neighborsMatrix)).*(patternMatrix);
%Vector of possible directions:
possibleMovesVector = sort(possibleMovesMatrix(possibleMovesMatrix(:) > 0));
%Random direction:
randomDirection = possibleMovesVector(randi(length(possibleMovesVector)));
directionCoordsVector = [[row (col-1)];[(row-1) col];[row (col+1)];[(row+1) col];[row col]];
res = [directionCoordsVector(randomDirection,1) directionCoordsVector(randomDirection,2)];
end
这个函数有点慢,当我运行分析器时它告诉我:
borderMatrix = [0 (row>1) 0;
(col>1) 1 (col<worldDimension);
0 (row<worldDimension) 0;];
需要 36% 的时间并且:randomDirection = possibleMove... 需要 15% 的时间。有没有办法可以加快这个过程?
也许我可以通过从主游戏板上立即获取生物坐标周围的空闲点来采取不同的方法?如果是这样,如果一个生物靠近棋盘的边界,我该如何获取子矩阵而不必处理越界索引?
谢了,兄弟们。