Update app.py
Browse files
app.py
CHANGED
|
@@ -11,70 +11,90 @@ app = Flask(__name__)
|
|
| 11 |
# IMPORTANT: Pour la production, utilisez une clé secrète forte et ne la codez pas en dur.
|
| 12 |
# Chargez-la depuis une variable d'environnement ou un fichier de configuration.
|
| 13 |
# Pour le DÉVELOPPEMENT UNIQUEMENT, une clé statique aide à éviter la perte de session due aux rechargements.
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
logging.warning("UTILISATION D'UNE CLÉ SECRÈTE STATIQUE POUR LE DÉVELOPPEMENT. NE PAS UTILISER EN PRODUCTION.")
|
| 17 |
else:
|
| 18 |
-
app.secret_key = os.environ.get("FLASK_SECRET_KEY"
|
| 19 |
-
if app.secret_key
|
|
|
|
| 20 |
logging.warning("FLASK_SECRET_KEY non définie. Utilisation d'une clé générée aléatoirement. "
|
| 21 |
"Les sessions ne persisteront pas entre les redémarrages du serveur de production.")
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
# --- Configuration du logging ---
|
| 25 |
logging.basicConfig(level=logging.DEBUG)
|
| 26 |
-
#
|
| 27 |
-
#
|
| 28 |
-
#
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
# --- Configuration de Stockfish ---
|
| 32 |
-
STOCKFISH_PATH = "stockfish"
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
for p in common_paths:
|
| 37 |
if os.path.exists(p) and os.access(p, os.X_OK):
|
| 38 |
STOCKFISH_PATH = p
|
| 39 |
-
found_stockfish = True
|
| 40 |
app.logger.info(f"Stockfish trouvé à: {STOCKFISH_PATH}")
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
def get_stockfish_engine():
|
| 47 |
"""Initialise et retourne une instance de Stockfish."""
|
| 48 |
-
if not
|
| 49 |
-
app.logger.error(
|
| 50 |
return None
|
| 51 |
try:
|
| 52 |
-
engine = Stockfish(path=STOCKFISH_PATH, depth=15, parameters={"Threads": 1, "Hash": 64})
|
| 53 |
if engine._stockfish.poll() is not None:
|
| 54 |
app.logger.error("Le processus Stockfish s'est terminé de manière inattendue lors de l'initialisation.")
|
| 55 |
raise StockfishException("Stockfish process terminated unexpectedly on init.")
|
| 56 |
-
|
| 57 |
engine.set_fen_position(chess.STARTING_FEN)
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
return engine
|
| 60 |
except Exception as e:
|
| 61 |
-
app.logger.error(f"Erreur lors de l'initialisation de Stockfish: {e}")
|
| 62 |
-
app.logger.error(f"Vérifiez que Stockfish est installé et que STOCKFISH_PATH ('{STOCKFISH_PATH}') est correct.")
|
| 63 |
return None
|
| 64 |
|
| 65 |
@app.route('/')
|
| 66 |
def index():
|
| 67 |
app.logger.debug(f"Session au début de GET /: {dict(session.items())}")
|
| 68 |
-
if 'board_fen' not in session:
|
| 69 |
app.logger.info("Initialisation de la session (board_fen, game_mode, player_color) dans GET /")
|
| 70 |
session['board_fen'] = chess.Board().fen()
|
| 71 |
session['game_mode'] = 'pvp'
|
| 72 |
-
session['player_color'] = 'white'
|
| 73 |
|
| 74 |
board = chess.Board(session['board_fen'])
|
| 75 |
app.logger.debug(f"Session à la fin de GET /: {dict(session.items())}")
|
| 76 |
return render_template('index.html',
|
| 77 |
-
initial_board_svg=chess.svg.board(board=board, size=400),
|
| 78 |
initial_fen=session['board_fen'],
|
| 79 |
game_mode=session['game_mode'],
|
| 80 |
player_color=session.get('player_color', 'white'),
|
|
@@ -85,18 +105,15 @@ def index():
|
|
| 85 |
|
| 86 |
def get_outcome_message(board):
|
| 87 |
if board.is_checkmate():
|
| 88 |
-
|
| 89 |
-
return f"Échec et mat ! {
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
if board.is_insufficient_material():
|
| 93 |
-
|
| 94 |
-
if board.
|
| 95 |
-
|
| 96 |
-
if board.
|
| 97 |
-
return "Répétition (5 fois). Partie nulle."
|
| 98 |
-
if board.is_variant_draw() or board.is_variant_loss() or board.is_variant_win(): # Autres types de fins
|
| 99 |
-
return "Partie terminée (variante)."
|
| 100 |
return ""
|
| 101 |
|
| 102 |
@app.route('/make_move', methods=['POST'])
|
|
@@ -104,9 +121,7 @@ def make_move():
|
|
| 104 |
app.logger.debug(f"Session au début de POST /make_move: {dict(session.items())}")
|
| 105 |
if 'board_fen' not in session:
|
| 106 |
app.logger.error("ERREUR CRITIQUE: 'board_fen' non trouvé dans la session pour POST /make_move!")
|
| 107 |
-
|
| 108 |
-
# session['board_fen'] = chess.Board().fen() # Réinitialisation d'urgence
|
| 109 |
-
return jsonify({'error': 'Erreur de session', 'board_fen' :'manquant. Veuillez rafraîchir ou réinitialiser.',
|
| 110 |
'fen': chess.Board().fen(), 'game_over': False, 'board_svg': chess.svg.board(board=chess.Board(), size=400)}), 500
|
| 111 |
|
| 112 |
board = chess.Board(session['board_fen'])
|
|
@@ -114,74 +129,79 @@ def make_move():
|
|
| 114 |
app.logger.info("Tentative de jouer alors que la partie est terminée.")
|
| 115 |
return jsonify({'error': 'La partie est terminée.', 'fen': board.fen(), 'game_over': True, 'outcome': get_outcome_message(board), 'board_svg': chess.svg.board(board=board, size=400)})
|
| 116 |
|
| 117 |
-
|
| 118 |
-
if not
|
| 119 |
app.logger.warning("Aucun mouvement fourni dans la requête POST /make_move.")
|
| 120 |
return jsonify({'error': 'Mouvement non fourni.', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
| 121 |
|
| 122 |
ai_move_made = False
|
| 123 |
ai_move_uci = None
|
| 124 |
last_player_move = None
|
|
|
|
| 125 |
|
| 126 |
try:
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
| 129 |
except ValueError:
|
| 130 |
try:
|
| 131 |
-
move = board.parse_san(
|
| 132 |
-
app.logger.info(f"Mouvement joueur (
|
| 133 |
except ValueError:
|
| 134 |
-
app.logger.warning(f"Mouvement invalide (ni UCI ni SAN): {
|
| 135 |
-
return jsonify({'error': f'Mouvement invalide: {
|
| 136 |
|
| 137 |
if move in board.legal_moves:
|
| 138 |
board.push(move)
|
| 139 |
-
last_player_move = move
|
|
|
|
| 140 |
session['board_fen'] = board.fen()
|
| 141 |
app.logger.info(f"Mouvement joueur {move.uci()} appliqué. Nouveau FEN: {board.fen()}")
|
| 142 |
|
| 143 |
if session.get('game_mode') == 'ai' and not board.is_game_over():
|
| 144 |
-
app.logger.info("Mode IA, tour de l'IA.")
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
if best_move_ai:
|
| 151 |
-
app.logger.info(f"Stockfish propose le coup: {best_move_ai}")
|
| 152 |
-
try:
|
| 153 |
-
ai_move_obj = board.parse_uci(best_move_ai)
|
| 154 |
-
board.push(ai_move_obj)
|
| 155 |
-
session['board_fen'] = board.fen()
|
| 156 |
-
ai_move_made = True
|
| 157 |
-
ai_move_uci = best_move_ai
|
| 158 |
-
app.logger.info(f"Mouvement IA {ai_move_uci} appliqué. Nouveau FEN: {board.fen()}")
|
| 159 |
-
except Exception as e:
|
| 160 |
-
app.logger.error(f"Erreur en appliquant le coup de l'IA {best_move_ai}: {e}")
|
| 161 |
-
else:
|
| 162 |
-
app.logger.warning("L'IA (Stockfish) n'a pas retourné de coup (peut-être mat/pat pour l'IA).")
|
| 163 |
-
stockfish_engine.send_quit_command()
|
| 164 |
-
app.logger.info("Moteur Stockfish arrêté après le coup de l'IA.")
|
| 165 |
else:
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
else:
|
| 169 |
-
app.logger.warning(f"Mouvement illégal tenté: {move.uci()} depuis FEN: {session['board_fen']}")
|
| 170 |
-
|
|
|
|
|
|
|
| 171 |
|
| 172 |
game_over = board.is_game_over()
|
| 173 |
outcome = get_outcome_message(board) if game_over else ""
|
| 174 |
if game_over:
|
| 175 |
app.logger.info(f"Partie terminée. Résultat: {outcome}")
|
| 176 |
|
| 177 |
-
# Déterminer le dernier coup à surligner
|
| 178 |
-
move_to_highlight = None
|
| 179 |
-
if ai_move_made:
|
| 180 |
-
move_to_highlight = ai_move_obj
|
| 181 |
-
elif last_player_move:
|
| 182 |
-
move_to_highlight = last_player_move
|
| 183 |
-
|
| 184 |
-
|
| 185 |
app.logger.debug(f"Session à la fin de POST /make_move: {dict(session.items())}")
|
| 186 |
return jsonify({
|
| 187 |
'fen': board.fen(),
|
|
@@ -196,9 +216,11 @@ def make_move():
|
|
| 196 |
def reset_game():
|
| 197 |
app.logger.debug(f"Session au début de POST /reset_game: {dict(session.items())}")
|
| 198 |
session['board_fen'] = chess.Board().fen()
|
| 199 |
-
# Conserver le mode
|
| 200 |
-
#
|
| 201 |
-
|
|
|
|
|
|
|
| 202 |
app.logger.info(f"Jeu réinitialisé. Nouveau FEN: {session['board_fen']}. Mode: {session.get('game_mode')}, Couleur joueur: {session.get('player_color')}")
|
| 203 |
|
| 204 |
board = chess.Board(session['board_fen'])
|
|
@@ -206,8 +228,8 @@ def reset_game():
|
|
| 206 |
return jsonify({
|
| 207 |
'fen': session['board_fen'],
|
| 208 |
'board_svg': chess.svg.board(board=board, size=400),
|
| 209 |
-
'game_mode': session.get('game_mode'
|
| 210 |
-
'player_color': session.get('player_color'
|
| 211 |
'turn': 'white' if board.turn == chess.WHITE else 'black',
|
| 212 |
'game_over': False,
|
| 213 |
'outcome': ""
|
|
@@ -217,20 +239,21 @@ def reset_game():
|
|
| 217 |
def set_mode_route():
|
| 218 |
app.logger.debug(f"Session au début de POST /set_mode: {dict(session.items())}")
|
| 219 |
mode = request.json.get('game_mode')
|
| 220 |
-
player_color = request.json.get('player_color', 'white')
|
| 221 |
|
| 222 |
if mode in ['pvp', 'ai']:
|
| 223 |
session['game_mode'] = mode
|
| 224 |
session['player_color'] = player_color
|
| 225 |
session['board_fen'] = chess.Board().fen()
|
| 226 |
-
app.logger.info(f"Mode de jeu réglé sur {mode}.
|
| 227 |
|
| 228 |
-
board = chess.Board()
|
| 229 |
initial_ai_move_uci = None
|
| 230 |
move_to_highlight_init = None
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
|
|
|
| 234 |
stockfish_engine = get_stockfish_engine()
|
| 235 |
if stockfish_engine:
|
| 236 |
stockfish_engine.set_fen_position(board.fen())
|
|
@@ -239,29 +262,29 @@ def set_mode_route():
|
|
| 239 |
try:
|
| 240 |
ai_move_obj = board.parse_uci(best_move_ai)
|
| 241 |
board.push(ai_move_obj)
|
| 242 |
-
session['board_fen'] = board.fen()
|
| 243 |
initial_ai_move_uci = best_move_ai
|
| 244 |
move_to_highlight_init = ai_move_obj
|
| 245 |
-
app.logger.info(f"Premier coup de l'IA (
|
| 246 |
except Exception as e:
|
| 247 |
-
app.logger.error(f"Erreur en appliquant le premier coup de l'IA {best_move_ai}: {e}")
|
| 248 |
-
|
| 249 |
stockfish_engine.send_quit_command()
|
| 250 |
app.logger.info("Moteur Stockfish arrêté après le premier coup de l'IA.")
|
| 251 |
else:
|
| 252 |
app.logger.error("Moteur Stockfish non disponible pour le premier coup de l'IA.")
|
| 253 |
-
|
|
|
|
| 254 |
|
| 255 |
app.logger.debug(f"Session à la fin de POST /set_mode: {dict(session.items())}")
|
| 256 |
return jsonify({
|
| 257 |
-
'message': f'Mode de jeu réglé sur {mode.upper()}. {"
|
| 258 |
'fen': session['board_fen'],
|
| 259 |
'board_svg': chess.svg.board(board=board, size=400, lastmove=move_to_highlight_init),
|
| 260 |
'game_mode': mode,
|
| 261 |
'player_color': player_color,
|
| 262 |
'turn': 'white' if board.turn == chess.WHITE else 'black',
|
| 263 |
'initial_ai_move_uci': initial_ai_move_uci,
|
| 264 |
-
'game_over': board.is_game_over(),
|
| 265 |
'outcome': get_outcome_message(board) if board.is_game_over() else ""
|
| 266 |
})
|
| 267 |
else:
|
|
@@ -269,7 +292,5 @@ def set_mode_route():
|
|
| 269 |
return jsonify({'error': 'Mode invalide'}), 400
|
| 270 |
|
| 271 |
if __name__ == '__main__':
|
| 272 |
-
#
|
| 273 |
-
|
| 274 |
-
# Le port 7860 est souvent utilisé par Gradio, assurez-vous qu'il n'y a pas de conflit.
|
| 275 |
-
app.run(debug=True, host='0.0.0.0', port=5000) # Utilisez un port standard comme 5000
|
|
|
|
| 11 |
# IMPORTANT: Pour la production, utilisez une clé secrète forte et ne la codez pas en dur.
|
| 12 |
# Chargez-la depuis une variable d'environnement ou un fichier de configuration.
|
| 13 |
# Pour le DÉVELOPPEMENT UNIQUEMENT, une clé statique aide à éviter la perte de session due aux rechargements.
|
| 14 |
+
IS_DEBUG_MODE = os.environ.get("FLASK_DEBUG", "0") == "1" or app.debug
|
| 15 |
+
|
| 16 |
+
if IS_DEBUG_MODE:
|
| 17 |
+
app.secret_key = 'dev_secret_key_pour_eviter_perte_session_rechargement_et_tests'
|
| 18 |
logging.warning("UTILISATION D'UNE CLÉ SECRÈTE STATIQUE POUR LE DÉVELOPPEMENT. NE PAS UTILISER EN PRODUCTION.")
|
| 19 |
else:
|
| 20 |
+
app.secret_key = os.environ.get("FLASK_SECRET_KEY")
|
| 21 |
+
if not app.secret_key:
|
| 22 |
+
app.secret_key = os.urandom(32) # Génère une clé plus longue pour la prod si non définie
|
| 23 |
logging.warning("FLASK_SECRET_KEY non définie. Utilisation d'une clé générée aléatoirement. "
|
| 24 |
"Les sessions ne persisteront pas entre les redémarrages du serveur de production.")
|
| 25 |
|
| 26 |
+
# --- Configuration des Cookies de Session ---
|
| 27 |
+
# Ces configurations sont importantes pour le développement en HTTP.
|
| 28 |
+
app.config.update(
|
| 29 |
+
SESSION_COOKIE_SECURE=False, # Permet les cookies de session sur HTTP (développement)
|
| 30 |
+
SESSION_COOKIE_HTTPONLY=True, # Empêche l'accès au cookie via JavaScript (bonne pratique)
|
| 31 |
+
SESSION_COOKIE_SAMESITE='Lax', # Politique SameSite raisonnable pour la plupart des cas
|
| 32 |
+
# PERMANENT_SESSION_LIFETIME=timedelta(days=7) # Optionnel: durée de vie de la session
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
|
| 36 |
# --- Configuration du logging ---
|
| 37 |
logging.basicConfig(level=logging.DEBUG)
|
| 38 |
+
# Pour réduire le bruit des requêtes GET/POST en console en production:
|
| 39 |
+
# if not IS_DEBUG_MODE:
|
| 40 |
+
# werkzeug_logger = logging.getLogger('werkzeug')
|
| 41 |
+
# werkzeug_logger.setLevel(logging.WARNING)
|
| 42 |
|
| 43 |
|
| 44 |
# --- Configuration de Stockfish ---
|
| 45 |
+
STOCKFISH_PATH = "stockfish"
|
| 46 |
+
def find_stockfish():
|
| 47 |
+
global STOCKFISH_PATH
|
| 48 |
+
if os.path.exists(STOCKFISH_PATH) and os.access(STOCKFISH_PATH, os.X_OK):
|
| 49 |
+
app.logger.info(f"Stockfish trouvé directement à: {STOCKFISH_PATH}")
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
common_paths = ["/usr/games/stockfish", "/usr/local/bin/stockfish", "/opt/homebrew/bin/stockfish", "stockfish.exe", "./stockfish"]
|
| 53 |
for p in common_paths:
|
| 54 |
if os.path.exists(p) and os.access(p, os.X_OK):
|
| 55 |
STOCKFISH_PATH = p
|
|
|
|
| 56 |
app.logger.info(f"Stockfish trouvé à: {STOCKFISH_PATH}")
|
| 57 |
+
return True
|
| 58 |
+
app.logger.warning(f"AVERTISSEMENT: Stockfish non trouvé. L'IA ne fonctionnera pas. "
|
| 59 |
+
"Veuillez installer Stockfish et/ou configurer STOCKFISH_PATH.")
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
HAS_STOCKFISH = find_stockfish()
|
| 63 |
+
|
| 64 |
|
| 65 |
def get_stockfish_engine():
|
| 66 |
"""Initialise et retourne une instance de Stockfish."""
|
| 67 |
+
if not HAS_STOCKFISH:
|
| 68 |
+
app.logger.error("Stockfish non disponible. L'IA ne peut pas démarrer.")
|
| 69 |
return None
|
| 70 |
try:
|
| 71 |
+
engine = Stockfish(path=STOCKFISH_PATH, depth=15, parameters={"Threads": 1, "Hash": 64})
|
| 72 |
if engine._stockfish.poll() is not None:
|
| 73 |
app.logger.error("Le processus Stockfish s'est terminé de manière inattendue lors de l'initialisation.")
|
| 74 |
raise StockfishException("Stockfish process terminated unexpectedly on init.")
|
| 75 |
+
# Test rapide pour s'assurer que Stockfish répond
|
| 76 |
engine.set_fen_position(chess.STARTING_FEN)
|
| 77 |
+
engine.get_best_move()
|
| 78 |
+
engine.set_fen_position(chess.STARTING_FEN) # Reset après test
|
| 79 |
+
app.logger.info(f"Moteur Stockfish initialisé avec succès depuis {STOCKFISH_PATH}.")
|
| 80 |
return engine
|
| 81 |
except Exception as e:
|
| 82 |
+
app.logger.error(f"Erreur lors de l'initialisation de Stockfish ({STOCKFISH_PATH}): {e}", exc_info=True)
|
|
|
|
| 83 |
return None
|
| 84 |
|
| 85 |
@app.route('/')
|
| 86 |
def index():
|
| 87 |
app.logger.debug(f"Session au début de GET /: {dict(session.items())}")
|
| 88 |
+
if 'board_fen' not in session or 'game_mode' not in session:
|
| 89 |
app.logger.info("Initialisation de la session (board_fen, game_mode, player_color) dans GET /")
|
| 90 |
session['board_fen'] = chess.Board().fen()
|
| 91 |
session['game_mode'] = 'pvp'
|
| 92 |
+
session['player_color'] = 'white' # Couleur du joueur humain si mode AI
|
| 93 |
|
| 94 |
board = chess.Board(session['board_fen'])
|
| 95 |
app.logger.debug(f"Session à la fin de GET /: {dict(session.items())}")
|
| 96 |
return render_template('index.html',
|
| 97 |
+
initial_board_svg=chess.svg.board(board=board, size=400),
|
| 98 |
initial_fen=session['board_fen'],
|
| 99 |
game_mode=session['game_mode'],
|
| 100 |
player_color=session.get('player_color', 'white'),
|
|
|
|
| 105 |
|
| 106 |
def get_outcome_message(board):
|
| 107 |
if board.is_checkmate():
|
| 108 |
+
winner_color = "Blancs" if board.turn == chess.BLACK else "Noirs"
|
| 109 |
+
return f"Échec et mat ! {winner_color} gagnent."
|
| 110 |
+
# Vérifier d'abord les conditions de nullité spécifiques avant is_game_over() générique
|
| 111 |
+
if board.is_stalemate(): return "Pat ! Partie nulle."
|
| 112 |
+
if board.is_insufficient_material(): return "Matériel insuffisant. Partie nulle."
|
| 113 |
+
if board.is_seventyfive_moves(): return "Règle des 75 coups. Partie nulle."
|
| 114 |
+
if board.is_fivefold_repetition(): return "Répétition (5 fois). Partie nulle."
|
| 115 |
+
# if board.is_variant_draw(): return "Partie nulle (variante)." # Moins courant pour échecs std
|
| 116 |
+
if board.is_game_over(): return "Partie terminée." # Cas générique si aucune des conditions ci-dessus
|
|
|
|
|
|
|
|
|
|
| 117 |
return ""
|
| 118 |
|
| 119 |
@app.route('/make_move', methods=['POST'])
|
|
|
|
| 121 |
app.logger.debug(f"Session au début de POST /make_move: {dict(session.items())}")
|
| 122 |
if 'board_fen' not in session:
|
| 123 |
app.logger.error("ERREUR CRITIQUE: 'board_fen' non trouvé dans la session pour POST /make_move!")
|
| 124 |
+
return jsonify({'error': 'Erreur de session, "board_fen" manquant. Veuillez rafraîchir ou réinitialiser.',
|
|
|
|
|
|
|
| 125 |
'fen': chess.Board().fen(), 'game_over': False, 'board_svg': chess.svg.board(board=chess.Board(), size=400)}), 500
|
| 126 |
|
| 127 |
board = chess.Board(session['board_fen'])
|
|
|
|
| 129 |
app.logger.info("Tentative de jouer alors que la partie est terminée.")
|
| 130 |
return jsonify({'error': 'La partie est terminée.', 'fen': board.fen(), 'game_over': True, 'outcome': get_outcome_message(board), 'board_svg': chess.svg.board(board=board, size=400)})
|
| 131 |
|
| 132 |
+
move_uci_san = request.json.get('move')
|
| 133 |
+
if not move_uci_san:
|
| 134 |
app.logger.warning("Aucun mouvement fourni dans la requête POST /make_move.")
|
| 135 |
return jsonify({'error': 'Mouvement non fourni.', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
| 136 |
|
| 137 |
ai_move_made = False
|
| 138 |
ai_move_uci = None
|
| 139 |
last_player_move = None
|
| 140 |
+
move_to_highlight = None
|
| 141 |
|
| 142 |
try:
|
| 143 |
+
# python-chess parse_uci peut aussi prendre SAN pour des coups simples.
|
| 144 |
+
# Pour être plus strict, on pourrait essayer parse_uci d'abord, puis parse_san.
|
| 145 |
+
move = board.parse_uci(move_uci_san)
|
| 146 |
+
app.logger.info(f"Mouvement joueur (tentative UCI): {move.uci()}")
|
| 147 |
except ValueError:
|
| 148 |
try:
|
| 149 |
+
move = board.parse_san(move_uci_san)
|
| 150 |
+
app.logger.info(f"Mouvement joueur (tentative SAN): {board.san(move)}")
|
| 151 |
except ValueError:
|
| 152 |
+
app.logger.warning(f"Mouvement invalide (ni UCI ni SAN): {move_uci_san} pour FEN {board.fen()}")
|
| 153 |
+
return jsonify({'error': f'Mouvement invalide: {move_uci_san}', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
| 154 |
|
| 155 |
if move in board.legal_moves:
|
| 156 |
board.push(move)
|
| 157 |
+
last_player_move = move
|
| 158 |
+
move_to_highlight = move # Le coup du joueur est le dernier pour l'instant
|
| 159 |
session['board_fen'] = board.fen()
|
| 160 |
app.logger.info(f"Mouvement joueur {move.uci()} appliqué. Nouveau FEN: {board.fen()}")
|
| 161 |
|
| 162 |
if session.get('game_mode') == 'ai' and not board.is_game_over():
|
| 163 |
+
app.logger.info(f"Mode IA, tour de l'IA. Joueur humain est {session.get('player_color')}.")
|
| 164 |
+
current_turn_is_ai_turn = (session.get('player_color') == 'white' and board.turn == chess.BLACK) or \
|
| 165 |
+
(session.get('player_color') == 'black' and board.turn == chess.WHITE)
|
| 166 |
+
|
| 167 |
+
if not current_turn_is_ai_turn:
|
| 168 |
+
app.logger.error(f"Logique d'alternance erronée: C'est le tour de {board.turn}, mais l'IA ne devrait pas jouer.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
else:
|
| 170 |
+
stockfish_engine = get_stockfish_engine()
|
| 171 |
+
if stockfish_engine:
|
| 172 |
+
stockfish_engine.set_fen_position(board.fen())
|
| 173 |
+
best_move_ai = stockfish_engine.get_best_move() # ou get_best_move_time(500)
|
| 174 |
+
if best_move_ai:
|
| 175 |
+
app.logger.info(f"Stockfish propose le coup: {best_move_ai}")
|
| 176 |
+
try:
|
| 177 |
+
ai_move_obj = board.parse_uci(best_move_ai)
|
| 178 |
+
board.push(ai_move_obj)
|
| 179 |
+
session['board_fen'] = board.fen()
|
| 180 |
+
ai_move_made = True
|
| 181 |
+
ai_move_uci = best_move_ai
|
| 182 |
+
move_to_highlight = ai_move_obj # Le coup de l'IA est le plus récent
|
| 183 |
+
app.logger.info(f"Mouvement IA {ai_move_uci} appliqué. Nouveau FEN: {board.fen()}")
|
| 184 |
+
except Exception as e:
|
| 185 |
+
app.logger.error(f"Erreur en appliquant le coup de l'IA {best_move_ai}: {e}", exc_info=True)
|
| 186 |
+
else:
|
| 187 |
+
app.logger.warning("L'IA (Stockfish) n'a pas retourné de coup.")
|
| 188 |
+
stockfish_engine.send_quit_command()
|
| 189 |
+
app.logger.info("Moteur Stockfish arrêté après le coup de l'IA.")
|
| 190 |
+
else:
|
| 191 |
+
app.logger.error("Moteur Stockfish non disponible pour le coup de l'IA.")
|
| 192 |
+
# Ne pas retourner d'erreur au client ici, laisser la partie continuer sans coup IA pour ce tour
|
| 193 |
+
# ou envisager une meilleure gestion de cet échec.
|
| 194 |
else:
|
| 195 |
+
app.logger.warning(f"Mouvement illégal tenté: {move.uci() if hasattr(move, 'uci') else move_uci_san} depuis FEN: {session['board_fen']}")
|
| 196 |
+
legal_moves_str = ", ".join([board.san(m) for m in board.legal_moves])
|
| 197 |
+
app.logger.debug(f"Coups légaux: {legal_moves_str[:200]}") # Limiter la longueur
|
| 198 |
+
return jsonify({'error': f'Mouvement illégal: {move.uci() if hasattr(move, "uci") else move_uci_san}', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
| 199 |
|
| 200 |
game_over = board.is_game_over()
|
| 201 |
outcome = get_outcome_message(board) if game_over else ""
|
| 202 |
if game_over:
|
| 203 |
app.logger.info(f"Partie terminée. Résultat: {outcome}")
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
app.logger.debug(f"Session à la fin de POST /make_move: {dict(session.items())}")
|
| 206 |
return jsonify({
|
| 207 |
'fen': board.fen(),
|
|
|
|
| 216 |
def reset_game():
|
| 217 |
app.logger.debug(f"Session au début de POST /reset_game: {dict(session.items())}")
|
| 218 |
session['board_fen'] = chess.Board().fen()
|
| 219 |
+
# Conserver le mode et la couleur, ou les réinitialiser si nécessaire.
|
| 220 |
+
# Si le mode ou la couleur ne sont pas dans la session, les initialiser.
|
| 221 |
+
if 'game_mode' not in session: session['game_mode'] = 'pvp'
|
| 222 |
+
if 'player_color' not in session: session['player_color'] = 'white'
|
| 223 |
+
|
| 224 |
app.logger.info(f"Jeu réinitialisé. Nouveau FEN: {session['board_fen']}. Mode: {session.get('game_mode')}, Couleur joueur: {session.get('player_color')}")
|
| 225 |
|
| 226 |
board = chess.Board(session['board_fen'])
|
|
|
|
| 228 |
return jsonify({
|
| 229 |
'fen': session['board_fen'],
|
| 230 |
'board_svg': chess.svg.board(board=board, size=400),
|
| 231 |
+
'game_mode': session.get('game_mode'),
|
| 232 |
+
'player_color': session.get('player_color'),
|
| 233 |
'turn': 'white' if board.turn == chess.WHITE else 'black',
|
| 234 |
'game_over': False,
|
| 235 |
'outcome': ""
|
|
|
|
| 239 |
def set_mode_route():
|
| 240 |
app.logger.debug(f"Session au début de POST /set_mode: {dict(session.items())}")
|
| 241 |
mode = request.json.get('game_mode')
|
| 242 |
+
player_color = request.json.get('player_color', 'white') # Couleur du joueur humain
|
| 243 |
|
| 244 |
if mode in ['pvp', 'ai']:
|
| 245 |
session['game_mode'] = mode
|
| 246 |
session['player_color'] = player_color
|
| 247 |
session['board_fen'] = chess.Board().fen()
|
| 248 |
+
app.logger.info(f"Mode de jeu réglé sur {mode}. Joueur humain: {player_color if mode == 'ai' else 'N/A'}. FEN réinitialisé.")
|
| 249 |
|
| 250 |
+
board = chess.Board()
|
| 251 |
initial_ai_move_uci = None
|
| 252 |
move_to_highlight_init = None
|
| 253 |
|
| 254 |
+
# Si le mode est IA et le joueur humain a choisi les Noirs, l'IA (Blancs) joue en premier.
|
| 255 |
+
if mode == 'ai' and player_color == 'black':
|
| 256 |
+
app.logger.info("L'IA (Blancs) commence la partie.")
|
| 257 |
stockfish_engine = get_stockfish_engine()
|
| 258 |
if stockfish_engine:
|
| 259 |
stockfish_engine.set_fen_position(board.fen())
|
|
|
|
| 262 |
try:
|
| 263 |
ai_move_obj = board.parse_uci(best_move_ai)
|
| 264 |
board.push(ai_move_obj)
|
| 265 |
+
session['board_fen'] = board.fen()
|
| 266 |
initial_ai_move_uci = best_move_ai
|
| 267 |
move_to_highlight_init = ai_move_obj
|
| 268 |
+
app.logger.info(f"Premier coup de l'IA (Blancs): {initial_ai_move_uci}. Nouveau FEN: {board.fen()}")
|
| 269 |
except Exception as e:
|
| 270 |
+
app.logger.error(f"Erreur en appliquant le premier coup de l'IA {best_move_ai}: {e}", exc_info=True)
|
|
|
|
| 271 |
stockfish_engine.send_quit_command()
|
| 272 |
app.logger.info("Moteur Stockfish arrêté après le premier coup de l'IA.")
|
| 273 |
else:
|
| 274 |
app.logger.error("Moteur Stockfish non disponible pour le premier coup de l'IA.")
|
| 275 |
+
# Pas idéal de retourner une erreur ici, le client pourrait être bloqué.
|
| 276 |
+
# On pourrait laisser le FEN initial.
|
| 277 |
|
| 278 |
app.logger.debug(f"Session à la fin de POST /set_mode: {dict(session.items())}")
|
| 279 |
return jsonify({
|
| 280 |
+
'message': f'Mode de jeu réglé sur {mode.upper()}. {"Vous jouez " + player_color.capitalize() if mode == "ai" else ""}',
|
| 281 |
'fen': session['board_fen'],
|
| 282 |
'board_svg': chess.svg.board(board=board, size=400, lastmove=move_to_highlight_init),
|
| 283 |
'game_mode': mode,
|
| 284 |
'player_color': player_color,
|
| 285 |
'turn': 'white' if board.turn == chess.WHITE else 'black',
|
| 286 |
'initial_ai_move_uci': initial_ai_move_uci,
|
| 287 |
+
'game_over': board.is_game_over(), # Devrait être False ici en général
|
| 288 |
'outcome': get_outcome_message(board) if board.is_game_over() else ""
|
| 289 |
})
|
| 290 |
else:
|
|
|
|
| 292 |
return jsonify({'error': 'Mode invalide'}), 400
|
| 293 |
|
| 294 |
if __name__ == '__main__':
|
| 295 |
+
# IS_DEBUG_MODE est défini plus haut
|
| 296 |
+
app.run(debug=IS_DEBUG_MODE, host='0.0.0.0', port=5000)
|
|
|
|
|
|