fork download
  1. # tictactoe_clean.py
  2. import math
  3.  
  4. HUMAN = "X"
  5. AI = "O"
  6.  
  7. def display_board(board):
  8. print()
  9. for i in range(3):
  10. row = board[3*i:3*i+3]
  11. print(" " + " | ".join(cell if cell != " " else str(3*i + j + 1) for j,cell in enumerate(row)))
  12. if i < 2:
  13. print("---+---+---")
  14. print()
  15.  
  16. def check_winner(board):
  17. wins = [
  18. (0,1,2),(3,4,5),(6,7,8),
  19. (0,3,6),(1,4,7),(2,5,8),
  20. (0,4,8),(2,4,6)
  21. ]
  22. for a,b,c in wins:
  23. if board[a] == board[b] == board[c] and board[a] != " ":
  24. return board[a]
  25. if " " not in board:
  26. return "Tie"
  27. return None
  28.  
  29. def available_moves(board):
  30. return [i for i,cell in enumerate(board) if cell == " "]
  31.  
  32. def minimax(board, player):
  33. winner = check_winner(board)
  34. if winner == AI:
  35. return (1, None)
  36. elif winner == HUMAN:
  37. return (-1, None)
  38. elif winner == "Tie":
  39. return (0, None)
  40.  
  41. if player == AI:
  42. best_score = -math.inf
  43. best_move = None
  44. for move in available_moves(board):
  45. board[move] = AI
  46. score, _ = minimax(board, HUMAN)
  47. board[move] = " "
  48. if score > best_score:
  49. best_score = score
  50. best_move = move
  51. return (best_score, best_move)
  52. else:
  53. best_score = math.inf
  54. best_move = None
  55. for move in available_moves(board):
  56. board[move] = HUMAN
  57. score, _ = minimax(board, AI)
  58. board[move] = " "
  59. if score < best_score:
  60. best_score = score
  61. best_move = move
  62. return (best_score, best_move)
  63.  
  64. def human_move(board):
  65. while True:
  66. try:
  67. s = input("Ton coup (1-9) : ").strip()
  68. choice = int(s)
  69. idx = choice - 1
  70. if idx not in range(9):
  71. print("Choix invalide. Entre un nombre entre 1 et 9.")
  72. elif board[idx] != " ":
  73. print("Case déjà prise, choisis une autre case.")
  74. else:
  75. board[idx] = HUMAN
  76. return
  77. except ValueError:
  78. print("Entrée non valide. Entre un nombre entier entre 1 et 9.")
  79. except (EOFError, KeyboardInterrupt):
  80. print("\nEntrée interrompue. Fin du jeu.")
  81. raise SystemExit
  82.  
  83. def ai_move(board):
  84. _, move = minimax(board, AI)
  85. if move is None:
  86. moves = available_moves(board)
  87. move = moves[0] if moves else None
  88. if move is not None:
  89. board[move] = AI
  90. print("L'IA joue en case {}.".format(move+1))
  91.  
  92. def play():
  93. board = [" "] * 9
  94. print("Tic-Tac-Toe : tu es 'X', l'IA est 'O'.")
  95. first = ""
  96. try:
  97. while first.lower() not in ("j", "i"):
  98. first = input("Qui commence ? (J pour toi / I pour l'IA) : ").strip() or "J"
  99. except (EOFError, KeyboardInterrupt):
  100. print("\nEntrée interrompue. Fin du jeu.")
  101. return
  102.  
  103. human_turn = (first.lower() == "j")
  104. display_board(board)
  105.  
  106. while True:
  107. if human_turn:
  108. human_move(board)
  109. else:
  110. ai_move(board)
  111.  
  112. display_board(board)
  113. winner = check_winner(board)
  114. if winner:
  115. if winner == HUMAN:
  116. print("Bravo — tu as gagné !")
  117. elif winner == AI:
  118. print("Dommage, l'IA a gagné.")
  119. else:
  120. print("Égalité !")
  121. break
  122.  
  123. human_turn = not human_turn
  124.  
  125. if __name__ == "__main__":
  126. play()
  127.  
Success #stdin #stdout 0.01s 7196KB
stdin
Standard input is empty
stdout
Tic-Tac-Toe : tu es 'X', l'IA est 'O'.
Qui commence ? (J pour toi / I pour l'IA) : 
Entrée interrompue. Fin du jeu.