AIロジック
AIはMinimaxアルゴリズムを採用し、5段階の難易度で最適手を選択。盤面評価関数はコマ数の差を基準に、計算負荷を抑えつつ強いプレイを実現します。
設計思想
Minimaxは再帰的に盤面を探索し、最適手を評価。深さ(`aiLevel`)に応じて探索範囲を調整し、レベル1はランダム、レベル5は最大5手先まで読む。評価関数は単純なコマ数差だが、角や辺の戦略的重要性も考慮可能。盤面コピーを用いてゲーム状態と分離し、試行中の副作用を排除。
サンプルコード
function minimax(boardState, player, depth) {
const moves = getValidMoves(boardState, player);
let bestScore = -Infinity;
let bestMove = moves[0];
for (const move of moves) {
const newBoard = simulateFlip(boardState, move.row, move.col, player);
const score = evaluateBoard(newBoard, player, depth - 1);
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
}
return bestMove;
}
function evaluateBoard(boardState, player, depth) {
if (depth === 0) {
return countPieces(boardState, player) - countPieces(boardState, player === 'black' ? 'white' : 'black');
}
const moves = getValidMoves(boardState, player);
if (moves.length === 0) {
return countPieces(boardState, player) - countPieces(boardState, player === 'black' ? 'white' : 'black');
}
let bestScore = -Infinity;
for (const move of moves) {
const newBoard = simulateFlip(boardState, move.row, move.col, player);
const score = -evaluateBoard(newBoard, player === 'black' ? 'white' : 'black', depth - 1);
bestScore = Math.max(bestScore, score);
}
return bestScore;
}
解説
`minimax`は有効手を列挙し、各手をシミュレーションしてスコアを計算。`evaluateBoard`は深さ0でコマ数差を返し、それ以外は相手の最善手を再帰的に評価。時間計算量はO(M^D)で、Mは有効手数、Dは深さ。レベル5でも現実的な遅延(数百ms)で動作。将来の拡張として、アルファベータ枝刈りやヒューリスティック評価(角の重み付け)が可能。