|
from flask import Flask, render_template, request, jsonify, session |
|
import chess |
|
import chess.svg |
|
from stockfish import Stockfish, StockfishException |
|
import os |
|
import logging |
|
|
|
app = Flask(__name__) |
|
|
|
|
|
|
|
|
|
|
|
IS_DEBUG_MODE = os.environ.get("FLASK_DEBUG", "0") == "1" or app.debug |
|
|
|
if IS_DEBUG_MODE: |
|
app.secret_key = 'dev_secret_key_pour_eviter_perte_session_rechargement_et_tests' |
|
logging.warning("UTILISATION D'UNE CLÉ SECRÈTE STATIQUE POUR LE DÉVELOPPEMENT. NE PAS UTILISER EN PRODUCTION.") |
|
else: |
|
app.secret_key = os.environ.get("FLASK_SECRET_KEY") |
|
if not app.secret_key: |
|
app.secret_key = os.urandom(32) |
|
logging.warning("FLASK_SECRET_KEY non définie. Utilisation d'une clé générée aléatoirement. " |
|
"Les sessions ne persisteront pas entre les redémarrages du serveur de production.") |
|
|
|
|
|
|
|
app.config.update( |
|
SESSION_COOKIE_SECURE=False, |
|
SESSION_COOKIE_HTTPONLY=True, |
|
SESSION_COOKIE_SAMESITE='Lax', |
|
|
|
) |
|
|
|
|
|
|
|
logging.basicConfig(level=logging.DEBUG) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
STOCKFISH_PATH = "stockfish" |
|
def find_stockfish(): |
|
global STOCKFISH_PATH |
|
if os.path.exists(STOCKFISH_PATH) and os.access(STOCKFISH_PATH, os.X_OK): |
|
app.logger.info(f"Stockfish trouvé directement à: {STOCKFISH_PATH}") |
|
return True |
|
|
|
common_paths = ["/usr/games/stockfish", "/usr/local/bin/stockfish", "/opt/homebrew/bin/stockfish", "stockfish.exe", "./stockfish"] |
|
for p in common_paths: |
|
if os.path.exists(p) and os.access(p, os.X_OK): |
|
STOCKFISH_PATH = p |
|
app.logger.info(f"Stockfish trouvé à: {STOCKFISH_PATH}") |
|
return True |
|
app.logger.warning(f"AVERTISSEMENT: Stockfish non trouvé. L'IA ne fonctionnera pas. " |
|
"Veuillez installer Stockfish et/ou configurer STOCKFISH_PATH.") |
|
return False |
|
|
|
HAS_STOCKFISH = find_stockfish() |
|
|
|
|
|
def get_stockfish_engine(): |
|
"""Initialise et retourne une instance de Stockfish.""" |
|
if not HAS_STOCKFISH: |
|
app.logger.error("Stockfish non disponible. L'IA ne peut pas démarrer.") |
|
return None |
|
try: |
|
engine = Stockfish(path=STOCKFISH_PATH, depth=15, parameters={"Threads": 1, "Hash": 64}) |
|
if engine._stockfish.poll() is not None: |
|
app.logger.error("Le processus Stockfish s'est terminé de manière inattendue lors de l'initialisation.") |
|
raise StockfishException("Stockfish process terminated unexpectedly on init.") |
|
|
|
engine.set_fen_position(chess.STARTING_FEN) |
|
engine.get_best_move() |
|
engine.set_fen_position(chess.STARTING_FEN) |
|
app.logger.info(f"Moteur Stockfish initialisé avec succès depuis {STOCKFISH_PATH}.") |
|
return engine |
|
except Exception as e: |
|
app.logger.error(f"Erreur lors de l'initialisation de Stockfish ({STOCKFISH_PATH}): {e}", exc_info=True) |
|
return None |
|
|
|
@app.route('/') |
|
def index(): |
|
app.logger.debug(f"Session au début de GET /: {dict(session.items())}") |
|
if 'board_fen' not in session or 'game_mode' not in session: |
|
app.logger.info("Initialisation de la session (board_fen, game_mode, player_color) dans GET /") |
|
session['board_fen'] = chess.Board().fen() |
|
session['game_mode'] = 'pvp' |
|
session['player_color'] = 'white' |
|
|
|
board = chess.Board(session['board_fen']) |
|
app.logger.debug(f"Session à la fin de GET /: {dict(session.items())}") |
|
return render_template('index.html', |
|
initial_board_svg=chess.svg.board(board=board, size=400), |
|
initial_fen=session['board_fen'], |
|
game_mode=session['game_mode'], |
|
player_color=session.get('player_color', 'white'), |
|
is_game_over=board.is_game_over(), |
|
outcome=get_outcome_message(board) if board.is_game_over() else "", |
|
current_turn = 'white' if board.turn == chess.WHITE else 'black') |
|
|
|
|
|
def get_outcome_message(board): |
|
if board.is_checkmate(): |
|
winner_color = "Blancs" if board.turn == chess.BLACK else "Noirs" |
|
return f"Échec et mat ! {winner_color} gagnent." |
|
|
|
if board.is_stalemate(): return "Pat ! Partie nulle." |
|
if board.is_insufficient_material(): return "Matériel insuffisant. Partie nulle." |
|
if board.is_seventyfive_moves(): return "Règle des 75 coups. Partie nulle." |
|
if board.is_fivefold_repetition(): return "Répétition (5 fois). Partie nulle." |
|
|
|
if board.is_game_over(): return "Partie terminée." |
|
return "" |
|
|
|
@app.route('/make_move', methods=['POST']) |
|
def make_move(): |
|
app.logger.debug(f"Session au début de POST /make_move: {dict(session.items())}") |
|
if 'board_fen' not in session: |
|
app.logger.error("ERREUR CRITIQUE: 'board_fen' non trouvé dans la session pour POST /make_move!") |
|
return jsonify({'error': 'Erreur de session, "board_fen" manquant. Veuillez rafraîchir ou réinitialiser.', |
|
'fen': chess.Board().fen(), 'game_over': False, 'board_svg': chess.svg.board(board=chess.Board(), size=400)}), 500 |
|
|
|
board = chess.Board(session['board_fen']) |
|
if board.is_game_over(): |
|
app.logger.info("Tentative de jouer alors que la partie est terminée.") |
|
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)}) |
|
|
|
move_uci_san = request.json.get('move') |
|
if not move_uci_san: |
|
app.logger.warning("Aucun mouvement fourni dans la requête POST /make_move.") |
|
return jsonify({'error': 'Mouvement non fourni.', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)}) |
|
|
|
ai_move_made = False |
|
ai_move_uci = None |
|
last_player_move = None |
|
move_to_highlight = None |
|
|
|
try: |
|
|
|
|
|
move = board.parse_uci(move_uci_san) |
|
app.logger.info(f"Mouvement joueur (tentative UCI): {move.uci()}") |
|
except ValueError: |
|
try: |
|
move = board.parse_san(move_uci_san) |
|
app.logger.info(f"Mouvement joueur (tentative SAN): {board.san(move)}") |
|
except ValueError: |
|
app.logger.warning(f"Mouvement invalide (ni UCI ni SAN): {move_uci_san} pour FEN {board.fen()}") |
|
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)}) |
|
|
|
if move in board.legal_moves: |
|
board.push(move) |
|
last_player_move = move |
|
move_to_highlight = move |
|
session['board_fen'] = board.fen() |
|
app.logger.info(f"Mouvement joueur {move.uci()} appliqué. Nouveau FEN: {board.fen()}") |
|
|
|
if session.get('game_mode') == 'ai' and not board.is_game_over(): |
|
app.logger.info(f"Mode IA, tour de l'IA. Joueur humain est {session.get('player_color')}.") |
|
current_turn_is_ai_turn = (session.get('player_color') == 'white' and board.turn == chess.BLACK) or \ |
|
(session.get('player_color') == 'black' and board.turn == chess.WHITE) |
|
|
|
if not current_turn_is_ai_turn: |
|
app.logger.error(f"Logique d'alternance erronée: C'est le tour de {board.turn}, mais l'IA ne devrait pas jouer.") |
|
else: |
|
stockfish_engine = get_stockfish_engine() |
|
if stockfish_engine: |
|
stockfish_engine.set_fen_position(board.fen()) |
|
best_move_ai = stockfish_engine.get_best_move() |
|
if best_move_ai: |
|
app.logger.info(f"Stockfish propose le coup: {best_move_ai}") |
|
try: |
|
ai_move_obj = board.parse_uci(best_move_ai) |
|
board.push(ai_move_obj) |
|
session['board_fen'] = board.fen() |
|
ai_move_made = True |
|
ai_move_uci = best_move_ai |
|
move_to_highlight = ai_move_obj |
|
app.logger.info(f"Mouvement IA {ai_move_uci} appliqué. Nouveau FEN: {board.fen()}") |
|
except Exception as e: |
|
app.logger.error(f"Erreur en appliquant le coup de l'IA {best_move_ai}: {e}", exc_info=True) |
|
else: |
|
app.logger.warning("L'IA (Stockfish) n'a pas retourné de coup.") |
|
stockfish_engine.send_quit_command() |
|
app.logger.info("Moteur Stockfish arrêté après le coup de l'IA.") |
|
else: |
|
app.logger.error("Moteur Stockfish non disponible pour le coup de l'IA.") |
|
|
|
|
|
else: |
|
app.logger.warning(f"Mouvement illégal tenté: {move.uci() if hasattr(move, 'uci') else move_uci_san} depuis FEN: {session['board_fen']}") |
|
legal_moves_str = ", ".join([board.san(m) for m in board.legal_moves]) |
|
app.logger.debug(f"Coups légaux: {legal_moves_str[:200]}") |
|
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)}) |
|
|
|
game_over = board.is_game_over() |
|
outcome = get_outcome_message(board) if game_over else "" |
|
if game_over: |
|
app.logger.info(f"Partie terminée. Résultat: {outcome}") |
|
|
|
app.logger.debug(f"Session à la fin de POST /make_move: {dict(session.items())}") |
|
return jsonify({ |
|
'fen': board.fen(), |
|
'board_svg': chess.svg.board(board=board, size=400, lastmove=move_to_highlight), |
|
'game_over': game_over, |
|
'outcome': outcome, |
|
'ai_move_uci': ai_move_uci, |
|
'turn': 'white' if board.turn == chess.WHITE else 'black' |
|
}) |
|
|
|
@app.route('/reset_game', methods=['POST']) |
|
def reset_game(): |
|
app.logger.debug(f"Session au début de POST /reset_game: {dict(session.items())}") |
|
session['board_fen'] = chess.Board().fen() |
|
|
|
|
|
if 'game_mode' not in session: session['game_mode'] = 'pvp' |
|
if 'player_color' not in session: session['player_color'] = 'white' |
|
|
|
app.logger.info(f"Jeu réinitialisé. Nouveau FEN: {session['board_fen']}. Mode: {session.get('game_mode')}, Couleur joueur: {session.get('player_color')}") |
|
|
|
board = chess.Board(session['board_fen']) |
|
app.logger.debug(f"Session à la fin de POST /reset_game: {dict(session.items())}") |
|
return jsonify({ |
|
'fen': session['board_fen'], |
|
'board_svg': chess.svg.board(board=board, size=400), |
|
'game_mode': session.get('game_mode'), |
|
'player_color': session.get('player_color'), |
|
'turn': 'white' if board.turn == chess.WHITE else 'black', |
|
'game_over': False, |
|
'outcome': "" |
|
}) |
|
|
|
@app.route('/set_mode', methods=['POST']) |
|
def set_mode_route(): |
|
app.logger.debug(f"Session au début de POST /set_mode: {dict(session.items())}") |
|
mode = request.json.get('game_mode') |
|
player_color = request.json.get('player_color', 'white') |
|
|
|
if mode in ['pvp', 'ai']: |
|
session['game_mode'] = mode |
|
session['player_color'] = player_color |
|
session['board_fen'] = chess.Board().fen() |
|
app.logger.info(f"Mode de jeu réglé sur {mode}. Joueur humain: {player_color if mode == 'ai' else 'N/A'}. FEN réinitialisé.") |
|
|
|
board = chess.Board() |
|
initial_ai_move_uci = None |
|
move_to_highlight_init = None |
|
|
|
|
|
if mode == 'ai' and player_color == 'black': |
|
app.logger.info("L'IA (Blancs) commence la partie.") |
|
stockfish_engine = get_stockfish_engine() |
|
if stockfish_engine: |
|
stockfish_engine.set_fen_position(board.fen()) |
|
best_move_ai = stockfish_engine.get_best_move() |
|
if best_move_ai: |
|
try: |
|
ai_move_obj = board.parse_uci(best_move_ai) |
|
board.push(ai_move_obj) |
|
session['board_fen'] = board.fen() |
|
initial_ai_move_uci = best_move_ai |
|
move_to_highlight_init = ai_move_obj |
|
app.logger.info(f"Premier coup de l'IA (Blancs): {initial_ai_move_uci}. Nouveau FEN: {board.fen()}") |
|
except Exception as e: |
|
app.logger.error(f"Erreur en appliquant le premier coup de l'IA {best_move_ai}: {e}", exc_info=True) |
|
stockfish_engine.send_quit_command() |
|
app.logger.info("Moteur Stockfish arrêté après le premier coup de l'IA.") |
|
else: |
|
app.logger.error("Moteur Stockfish non disponible pour le premier coup de l'IA.") |
|
|
|
|
|
|
|
app.logger.debug(f"Session à la fin de POST /set_mode: {dict(session.items())}") |
|
return jsonify({ |
|
'message': f'Mode de jeu réglé sur {mode.upper()}. {"Vous jouez " + player_color.capitalize() if mode == "ai" else ""}', |
|
'fen': session['board_fen'], |
|
'board_svg': chess.svg.board(board=board, size=400, lastmove=move_to_highlight_init), |
|
'game_mode': mode, |
|
'player_color': player_color, |
|
'turn': 'white' if board.turn == chess.WHITE else 'black', |
|
'initial_ai_move_uci': initial_ai_move_uci, |
|
'game_over': board.is_game_over(), |
|
'outcome': get_outcome_message(board) if board.is_game_over() else "" |
|
}) |
|
else: |
|
app.logger.warning(f"Tentative de définir un mode de jeu invalide: {mode}") |
|
return jsonify({'error': 'Mode invalide'}), 400 |
|
|
|
if __name__ == '__main__': |
|
|
|
app.run(debug=IS_DEBUG_MODE, host='0.0.0.0', port=5000) |