From 62863dc4ef00acd5c02d1487e211de08b526cc40 Mon Sep 17 00:00:00 2001 From: letuaillon Date: Wed, 26 Apr 2023 09:03:18 +0200 Subject: [PATCH] =?UTF-8?q?ia=20avec=20m=C3=A9thode=20de=20deepSearch=20po?= =?UTF-8?q?ur=20toujours=20jouer=20le=20meilleur=20coup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- script1.js | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/script1.js b/script1.js index 012104e..40e8562 100644 --- a/script1.js +++ b/script1.js @@ -60,11 +60,74 @@ class AI { return available_moves[random_index]; } + minimax(matrix, depth, maximizingPlayer) { + const winner = this.check_winner(matrix); + + if (winner !== 0) { + return winner === this.player ? 10 - depth : depth - 10; + } + + if (matrix.is_full()) { + return 0; + } + + if (depth >= this.level) { + return 0; + } + + const opponent = 3 - this.player; + const currentPlayer = maximizingPlayer ? this.player : opponent; + + let bestScore = maximizingPlayer ? -Infinity : Infinity; + + for (let row = 0; row < 3; row++) { + for (let col = 0; col < 3; col++) { + if (matrix.cases[row][col] === 0) { + matrix.mark(row, col, currentPlayer); + const score = this.minimax(matrix, depth + 1, !maximizingPlayer); + matrix.cases[row][col] = 0; + matrix.marked_case--; + + bestScore = maximizingPlayer ? Math.max(bestScore, score) : Math.min(bestScore, score); + } + } + } + + return bestScore; + } + + check_winner(matrix) { + for (let player = 1; player <= 2; player++) { + if (matrix.check_win(player)) { + return player; + } + } + return 0; + } - move(matrix) { - return this.random_move(matrix); + let bestScore = -Infinity; + let bestMove = null; + + for (let row = 0; row < 3; row++) { + for (let col = 0; col < 3; col++) { + if (matrix.cases[row][col] === 0) { + matrix.mark(row, col, this.player); + const score = this.minimax(matrix, 1, false); + matrix.cases[row][col] = 0; + matrix.marked_case--; + + if (score > bestScore) { + bestScore = score; + bestMove = [row, col]; + } + } + } + } + + return bestMove; } + } class Game {