import numpy as np import random import random class TicTacToe(): def init(self):…
- User
import numpy as np import random import random
class TicTacToe(): def init(self): self.state = np.zeros(9, dtype=int) # Initialisation de l’état self.done = False # Si le jeu est terminé self.q_table = dict() # Table Q pour l’apprentissage self.learning_rate = 0.1 # Taux d’apprentissage self.discount_rate = 0.95 # Facteur de remise self.epsilon = 0.1 # Taux d’exploration self.player_turn = 1 # Tour du joueur
def reset(self): self.state.fill(0) self.done = False self.player_turn = 1 # Réinitialiser pour que le joueur 1 commence toujours def check_winner(self): win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] for condition in win_conditions: if self.state[condition[0]] ==self.state[condition[1]] == self.state[condition[2]] != 0: return True return False def step(self, action): if self.state[action] != 0 or self.done: return -1, True # Action invalide self.state[action] = self.player_turn if self.check_winner(): self.done = True return 1, True # Victoire if np.all(self.state != 0): self.done = True return 0.5, True # Match nul self.player_turn *= -1 # Changer de tour return 0, False # Pas de récompense, jeu continue def choose_action(self, state, explore=True): str_state = str(state) if str_state not in self.q_table: self.q_table[str_state] = np.zeros(9) - np.inf # Initialiser avec des valeurs infiniment négatives # Rendre les positions vides comme étant les seules sélectionnables. q_values = np.copy(self.q_table[str_state]) empty_positions = np.where(state == 0)[0] if explore and random.random() < self.epsilon: # Choix aléatoire parmi les cases vides return np.random.choice(empty_positions) else: # S’assurer que seulement les positions vides sont envisagées pour l’exploitation q_values_for_empty_positions = np.full(9, -np.inf) # Commencer avec toutes les positions comme étant infiniment mauvaises q_values_for_empty_positions[empty_positions] = q_values[empty_positions] # Appliquer les vraies valeurs Q pour les positions vides return np.argmax(q_values_for_empty_positions) def update_q_table(self, old_state, action, reward, new_state): old_str_state = str(old_state) new_str_state = str(new_state) future_rewards = 0 if new_str_state not in self.q_table else np.max(self.q_table[new_str_state]) self.q_table[old_str_state][action] += self.learning_rate * (reward + self.discount_rate * future_rewards - self.q_table[old_str_state][action])def train_agent(episodes=500): game = TicTacToe() for episode in range(episodes): game.reset() done = False while not done: state = game.state.copy() action = game.choose_action(state) reward, done = game.step(action) new_state = game.state.copy() game.update_q_table(state, action, reward, new_state)
def play_human(): game = TicTacToe() game.reset() human_player = -1 # Humain joue -1 (O), IA joue 1 (X) while True: print(f"État actuel du plateau:\n{np.reshape(game.state, (3, 3))}") if game.player_turn == human_player: valid_move = False while not valid_move: try: move = int(input("Votre prochain coup (0-8): ")) if game.state[move] == 0: valid_move = True else: print("Cette case est déjà prise. Essayez de nouveau.") except ValueError: print("Entrez un nombre valide.") else: move = game.choose_action(game.state, explore=False) print(f"Coup de l’IA: {move}") done = game.step(move) if done: print(f"Plateau final:\n{np.reshape(game.state, (3, 3))}") if game.check_winner(): print("L’IA gagne!” if game.player_turn == human_player else “Vous gagnez!") else: print("Match nul!") break
- Assistant
- User
- Assistant
- User
Entraînement de l’IA… :62: RuntimeWarning: invalid value encountered in scalar add self.q_table[old_str_state][action] += self.learning_rate * (reward + self.discount_rate * future_rewards - self.q_table[old_str_state][action]) :62: RuntimeWarning: invalid value encountered in scalar subtract self.q_table[old_str_state][action] += self.learning_rate * (reward + self.discount_rate * future_rewards - self.q_table[old_str_state][action]) Entraînement terminé. Jouez contre l’IA. État actuel du plateau: [[0 0 0] [0 0 0] [0 0 0]] Coup de l’IA: 0 Plateau final: [[1 0 0] [0 0 0] [0 0 0]] Match nul!
- Assistant
- User
aN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 7 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 8 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 NaN or Inf found in Q-table for state [0 0 0 0 0 0 0 0 0] and action 0 Entraînement terminé. Jouez contre l’IA. État actuel du plateau: [[0 0 0] [0 0 0] [0 0 0]] Coup de l’IA: 0 Plateau final: [[1 0 0] [0 0 0] [0 0 0]] Match nul!
- Assistant