Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,91 @@
|
|
1 |
from flask import Flask, render_template, request, jsonify, session
|
2 |
import chess
|
3 |
import chess.svg
|
4 |
-
from stockfish import Stockfish, StockfishException
|
5 |
import os
|
|
|
6 |
|
7 |
app = Flask(__name__)
|
8 |
-
app.secret_key = os.urandom(24) # Nécessaire pour les sessions
|
9 |
|
10 |
-
# Configuration
|
11 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
STOCKFISH_PATH = "stockfish" # Ou le chemin complet, ex: "/usr/games/stockfish"
|
13 |
-
if not os.path.exists(STOCKFISH_PATH):
|
14 |
-
|
15 |
-
|
16 |
for p in common_paths:
|
17 |
if os.path.exists(p) and os.access(p, os.X_OK):
|
18 |
STOCKFISH_PATH = p
|
|
|
|
|
19 |
break
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
|
25 |
def get_stockfish_engine():
|
26 |
"""Initialise et retourne une instance de Stockfish."""
|
|
|
|
|
|
|
27 |
try:
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
# Vérifier si l'engine est bien chargé
|
32 |
-
if not engine._stockfish.poll() is None: # Si le process s'est terminé
|
33 |
raise StockfishException("Stockfish process terminated unexpectedly on init.")
|
34 |
-
engine.get_best_move() # Test rapide
|
35 |
-
engine.set_fen_position(chess.STARTING_FEN)
|
|
|
36 |
return engine
|
37 |
except Exception as e:
|
38 |
-
|
39 |
-
|
40 |
return None
|
41 |
|
42 |
@app.route('/')
|
43 |
def index():
|
|
|
44 |
if 'board_fen' not in session:
|
|
|
45 |
session['board_fen'] = chess.Board().fen()
|
46 |
-
session['game_mode'] = 'pvp'
|
47 |
-
session['player_color'] = 'white'
|
48 |
|
49 |
board = chess.Board(session['board_fen'])
|
|
|
50 |
return render_template('index.html',
|
|
|
51 |
initial_fen=session['board_fen'],
|
52 |
-
board_svg=chess.svg.board(board=board, size=400),
|
53 |
game_mode=session['game_mode'],
|
54 |
player_color=session.get('player_color', 'white'),
|
55 |
is_game_over=board.is_game_over(),
|
56 |
-
outcome=get_outcome_message(board) if board.is_game_over() else ""
|
|
|
|
|
57 |
|
58 |
def get_outcome_message(board):
|
59 |
if board.is_checkmate():
|
60 |
-
winner = "Blancs" if board.turn == chess.BLACK else "Noirs"
|
61 |
return f"Échec et mat ! {winner} gagnent."
|
62 |
if board.is_stalemate():
|
63 |
return "Pat ! Partie nulle."
|
@@ -67,63 +95,97 @@ def get_outcome_message(board):
|
|
67 |
return "Règle des 75 coups. Partie nulle."
|
68 |
if board.is_fivefold_repetition():
|
69 |
return "Répétition (5 fois). Partie nulle."
|
|
|
|
|
70 |
return ""
|
71 |
|
72 |
@app.route('/make_move', methods=['POST'])
|
73 |
def make_move():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
board = chess.Board(session['board_fen'])
|
75 |
if board.is_game_over():
|
76 |
-
|
|
|
77 |
|
78 |
move_uci = request.json.get('move')
|
79 |
if not move_uci:
|
80 |
-
|
|
|
81 |
|
82 |
-
ai_move_made =
|
83 |
ai_move_uci = None
|
|
|
84 |
|
85 |
try:
|
86 |
move = board.parse_uci(move_uci)
|
|
|
87 |
except ValueError:
|
88 |
try:
|
89 |
-
|
90 |
-
|
91 |
except ValueError:
|
92 |
-
|
|
|
93 |
|
94 |
if move in board.legal_moves:
|
95 |
board.push(move)
|
|
|
96 |
session['board_fen'] = board.fen()
|
|
|
97 |
|
98 |
-
# Si mode AI et ce n'est pas la fin du jeu pour le joueur
|
99 |
if session.get('game_mode') == 'ai' and not board.is_game_over():
|
|
|
100 |
stockfish_engine = get_stockfish_engine()
|
101 |
if stockfish_engine:
|
102 |
stockfish_engine.set_fen_position(board.fen())
|
103 |
-
#
|
104 |
-
|
105 |
-
best_move_ai = stockfish_engine.get_best_move() # Utilise la profondeur configurée
|
106 |
if best_move_ai:
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
else:
|
116 |
-
|
117 |
-
|
118 |
else:
|
119 |
-
|
|
|
120 |
|
121 |
game_over = board.is_game_over()
|
122 |
outcome = get_outcome_message(board) if game_over else ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
|
|
124 |
return jsonify({
|
125 |
'fen': board.fen(),
|
126 |
-
'board_svg': chess.svg.board(board=board, size=400, lastmove=
|
127 |
'game_over': game_over,
|
128 |
'outcome': outcome,
|
129 |
'ai_move_uci': ai_move_uci,
|
@@ -132,59 +194,82 @@ def make_move():
|
|
132 |
|
133 |
@app.route('/reset_game', methods=['POST'])
|
134 |
def reset_game():
|
|
|
135 |
session['board_fen'] = chess.Board().fen()
|
136 |
-
#
|
137 |
-
#
|
138 |
-
# session['
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
return jsonify({
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
|
|
|
|
|
|
|
|
148 |
|
149 |
@app.route('/set_mode', methods=['POST'])
|
150 |
def set_mode_route():
|
|
|
151 |
mode = request.json.get('game_mode')
|
152 |
-
player_color = request.json.get('player_color', 'white')
|
153 |
|
154 |
if mode in ['pvp', 'ai']:
|
155 |
session['game_mode'] = mode
|
156 |
-
session['player_color'] = player_color
|
157 |
-
session['board_fen'] = chess.Board().fen()
|
|
|
158 |
|
159 |
-
board = chess.Board()
|
160 |
initial_ai_move_uci = None
|
|
|
161 |
|
162 |
-
|
163 |
-
|
164 |
stockfish_engine = get_stockfish_engine()
|
165 |
if stockfish_engine:
|
166 |
stockfish_engine.set_fen_position(board.fen())
|
167 |
best_move_ai = stockfish_engine.get_best_move()
|
168 |
if best_move_ai:
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
stockfish_engine.send_quit_command()
|
|
|
174 |
else:
|
175 |
-
|
|
|
176 |
|
|
|
177 |
return jsonify({
|
178 |
-
'message': f'Mode de jeu réglé sur {mode}. Joueur:
|
179 |
'fen': session['board_fen'],
|
180 |
-
'board_svg': chess.svg.board(board=board, size=400, lastmove=
|
181 |
'game_mode': mode,
|
182 |
'player_color': player_color,
|
183 |
'turn': 'white' if board.turn == chess.WHITE else 'black',
|
184 |
-
'initial_ai_move_uci': initial_ai_move_uci
|
|
|
|
|
185 |
})
|
186 |
-
|
187 |
-
|
|
|
188 |
|
189 |
if __name__ == '__main__':
|
190 |
-
|
|
|
|
|
|
|
|
1 |
from flask import Flask, render_template, request, jsonify, session
|
2 |
import chess
|
3 |
import chess.svg
|
4 |
+
from stockfish import Stockfish, StockfishException # Assurez-vous que ce module est accessible
|
5 |
import os
|
6 |
+
import logging
|
7 |
|
8 |
app = Flask(__name__)
|
|
|
9 |
|
10 |
+
# --- Configuration de la clé secrète ---
|
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 |
+
if app.debug:
|
15 |
+
app.secret_key = 'dev_secret_key_pour_eviter_perte_session_rechargement'
|
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", os.urandom(24))
|
19 |
+
if app.secret_key == os.urandom(24): # Check si on a dû fallback sur urandom
|
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 |
+
# Vous pouvez ajuster le niveau de logging pour la production, ex: logging.INFO
|
27 |
+
# werkzeug_logger = logging.getLogger('werkzeug')
|
28 |
+
# werkzeug_logger.setLevel(logging.INFO) # Pour réduire le bruit des requêtes GET/POST en console
|
29 |
+
|
30 |
+
|
31 |
+
# --- Configuration de Stockfish ---
|
32 |
STOCKFISH_PATH = "stockfish" # Ou le chemin complet, ex: "/usr/games/stockfish"
|
33 |
+
if not os.path.exists(STOCKFISH_PATH) or not os.access(STOCKFISH_PATH, os.X_OK):
|
34 |
+
common_paths = ["/usr/games/stockfish", "/usr/local/bin/stockfish", "/opt/homebrew/bin/stockfish", "stockfish.exe"]
|
35 |
+
found_stockfish = False
|
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 |
break
|
42 |
+
if not found_stockfish:
|
43 |
+
app.logger.warning(f"AVERTISSEMENT: Stockfish non trouvé à '{STOCKFISH_PATH}' ou dans les chemins communs. "
|
44 |
+
"L'IA ne fonctionnera pas. Veuillez installer Stockfish et/ou configurer STOCKFISH_PATH.")
|
|
|
45 |
|
46 |
def get_stockfish_engine():
|
47 |
"""Initialise et retourne une instance de Stockfish."""
|
48 |
+
if not os.path.exists(STOCKFISH_PATH) or not os.access(STOCKFISH_PATH, os.X_OK):
|
49 |
+
app.logger.error(f"Stockfish non exécutable à {STOCKFISH_PATH}. L'IA ne peut pas démarrer.")
|
50 |
+
return None
|
51 |
try:
|
52 |
+
engine = Stockfish(path=STOCKFISH_PATH, depth=15, parameters={"Threads": 1, "Hash": 64}) # Ajustez si besoin
|
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 |
+
engine.get_best_move() # Test rapide
|
57 |
+
engine.set_fen_position(chess.STARTING_FEN)
|
58 |
+
app.logger.info("Moteur Stockfish initialisé avec succès.")
|
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), # Renommé pour clarifier
|
78 |
initial_fen=session['board_fen'],
|
|
|
79 |
game_mode=session['game_mode'],
|
80 |
player_color=session.get('player_color', 'white'),
|
81 |
is_game_over=board.is_game_over(),
|
82 |
+
outcome=get_outcome_message(board) if board.is_game_over() else "",
|
83 |
+
current_turn = 'white' if board.turn == chess.WHITE else 'black')
|
84 |
+
|
85 |
|
86 |
def get_outcome_message(board):
|
87 |
if board.is_checkmate():
|
88 |
+
winner = "Blancs" if board.turn == chess.BLACK else "Noirs" # Celui dont ce n'est PAS le tour gagne
|
89 |
return f"Échec et mat ! {winner} gagnent."
|
90 |
if board.is_stalemate():
|
91 |
return "Pat ! Partie nulle."
|
|
|
95 |
return "Règle des 75 coups. Partie nulle."
|
96 |
if board.is_fivefold_repetition():
|
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'])
|
103 |
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 |
+
# Optionnel: essayer de réinitialiser ou informer le client
|
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'])
|
113 |
if board.is_game_over():
|
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 |
move_uci = request.json.get('move')
|
118 |
if not move_uci:
|
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 |
move = board.parse_uci(move_uci)
|
128 |
+
app.logger.info(f"Mouvement joueur (UCI parsed): {move.uci()}")
|
129 |
except ValueError:
|
130 |
try:
|
131 |
+
move = board.parse_san(move_uci) # Essayer SAN
|
132 |
+
app.logger.info(f"Mouvement joueur (SAN parsed): {board.san(move)}")
|
133 |
except ValueError:
|
134 |
+
app.logger.warning(f"Mouvement invalide (ni UCI ni SAN): {move_uci}")
|
135 |
+
return jsonify({'error': f'Mouvement invalide: {move_uci}', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
136 |
|
137 |
if move in board.legal_moves:
|
138 |
board.push(move)
|
139 |
+
last_player_move = move # Sauvegarder le dernier coup du joueur pour le SVG
|
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 |
stockfish_engine = get_stockfish_engine()
|
146 |
if stockfish_engine:
|
147 |
stockfish_engine.set_fen_position(board.fen())
|
148 |
+
# best_move_ai = stockfish_engine.get_best_move_time(500) # 0.5 seconde pour plus de réactivité
|
149 |
+
best_move_ai = stockfish_engine.get_best_move()
|
|
|
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 |
+
app.logger.error("Moteur Stockfish non disponible pour le coup de l'IA.")
|
167 |
+
return jsonify({'error': 'Moteur Stockfish non disponible.', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
168 |
else:
|
169 |
+
app.logger.warning(f"Mouvement illégal tenté: {move.uci()} depuis FEN: {session['board_fen']}")
|
170 |
+
return jsonify({'error': f'Mouvement illégal: {move.uci()}', 'fen': board.fen(), 'game_over': board.is_game_over(), 'board_svg': chess.svg.board(board=board, size=400)})
|
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(),
|
188 |
+
'board_svg': chess.svg.board(board=board, size=400, lastmove=move_to_highlight),
|
189 |
'game_over': game_over,
|
190 |
'outcome': outcome,
|
191 |
'ai_move_uci': ai_move_uci,
|
|
|
194 |
|
195 |
@app.route('/reset_game', methods=['POST'])
|
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 de jeu et la couleur du joueur actuels, ou les réinitialiser comme souhaité
|
200 |
+
# session['game_mode'] = 'pvp' # Optionnel: forcer un mode par défaut
|
201 |
+
# session['player_color'] = 'white' # Optionnel
|
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'])
|
205 |
+
app.logger.debug(f"Session à la fin de POST /reset_game: {dict(session.items())}")
|
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', 'pvp'), # Fournir une valeur par défaut si non défini
|
210 |
+
'player_color': session.get('player_color', 'white'),
|
211 |
+
'turn': 'white' if board.turn == chess.WHITE else 'black',
|
212 |
+
'game_over': False,
|
213 |
+
'outcome': ""
|
214 |
+
})
|
215 |
|
216 |
@app.route('/set_mode', methods=['POST'])
|
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}. Couleur joueur (si IA): {player_color}. FEN réinitialisé: {session['board_fen']}")
|
227 |
|
228 |
+
board = chess.Board() # Nouvelle instance pour la réponse initiale
|
229 |
initial_ai_move_uci = None
|
230 |
+
move_to_highlight_init = None
|
231 |
|
232 |
+
if mode == 'ai' and player_color == 'black': # L'IA (Blanc) joue en premier
|
233 |
+
app.logger.info("L'IA (Blanc) commence la partie.")
|
234 |
stockfish_engine = get_stockfish_engine()
|
235 |
if stockfish_engine:
|
236 |
stockfish_engine.set_fen_position(board.fen())
|
237 |
best_move_ai = stockfish_engine.get_best_move()
|
238 |
if best_move_ai:
|
239 |
+
try:
|
240 |
+
ai_move_obj = board.parse_uci(best_move_ai)
|
241 |
+
board.push(ai_move_obj)
|
242 |
+
session['board_fen'] = board.fen() # Mettre à jour le FEN de la session
|
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 (Blanc): {initial_ai_move_uci}. Nouveau FEN: {board.fen()}")
|
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 |
+
return jsonify({'error': 'Moteur Stockfish non disponible.'}), 500
|
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()}. {"Joueur: " + player_color.capitalize() if mode == "ai" else ""}',
|
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:
|
268 |
+
app.logger.warning(f"Tentative de définir un mode de jeu invalide: {mode}")
|
269 |
+
return jsonify({'error': 'Mode invalide'}), 400
|
270 |
|
271 |
if __name__ == '__main__':
|
272 |
+
# Pour la production, utilisez un serveur WSGI comme Gunicorn ou uWSGI.
|
273 |
+
# Par exemple: gunicorn -w 4 -b 0.0.0.0:5000 app:app
|
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
|