生き物を表す構造体の大きな正方行列があります。各クリーチャーは、左、上、右、または下に移動できます。空のセルの隣接するマトリックス位置をチェックして、新しい座標に対して次の計算を行います。
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%の時間がかかります。プロセスを加速する方法はありますか?
たぶん、メインのゲームボードからクリーチャーの座標の周りのフリースポットをすぐに取得することで、別のアプローチを取ることができますか?もしそうなら、クリーチャーが境界外のインデックスを処理する必要なしにボードの境界近くにある場合、どのようにサブマトリックスを取得しますか?
みんなありがとう。