File size: 5,367 Bytes
0efcaab
 
 
7bc796e
aa815df
0efcaab
7bc796e
0efcaab
 
 
 
 
 
 
 
 
 
7bc796e
 
 
 
0efcaab
7bc796e
0efcaab
 
 
 
7d3a75b
0efcaab
 
aa815df
0efcaab
 
 
 
 
 
 
7d3a75b
0efcaab
 
7bc796e
0efcaab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc968c
0efcaab
 
 
 
0cc968c
 
0efcaab
 
 
0cc968c
7bc796e
0efcaab
 
aa815df
0efcaab
 
 
 
 
 
7d3a75b
0efcaab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from flask import Flask, render_template, request, jsonify, session
from stockfish import Stockfish # Assurez-vous que le chemin est correct si besoin
import chess # python-chess

app = Flask(__name__)
app.secret_key = 'super_secret_key_for_session' # Important pour les sessions

# Pour simplifier, une instance globale. Pour une prod, gérer par session/jeu.
# Assurez-vous que le binaire stockfish est dans votre PATH ou spécifiez le chemin.
try:
    stockfish_path = "stockfish" # ou "/usr/games/stockfish" ou chemin vers votre binaire
    stockfish = Stockfish(path=stockfish_path, parameters={"Threads": 2, "Hash": 128})
except Exception as e:
    print(f"Erreur à l'initialisation de Stockfish: {e}")
    print("Veuillez vérifier que Stockfish est installé et accessible via le PATH, ou spécifiez le chemin correct.")
    # Vous pourriez vouloir quitter l'application ou avoir un mode dégradé.
    stockfish = None


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/new_game', methods=['POST'])
def new_game():
    if not stockfish:
        return jsonify({"error": "Stockfish non initialisé"}), 500
        
    data = request.json
    mode = data.get('mode', 'human') # 'ai' or 'human'
    
    initial_fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
    session['fen'] = initial_fen
    session['mode'] = mode
    session['turn'] = 'w' # White's turn
    session['history'] = []
    
    stockfish.set_fen_position(initial_fen)
    
    # python-chess board (optionnel mais recommandé)
    session['board_pgn'] = chess.Board().fen() # Stocker le FEN pour reconstruire

    return jsonify({
        "fen": initial_fen,
        "turn": session['turn'],
        "message": "Nouvelle partie commencée."
    })

@app.route('/move', methods=['POST'])
def handle_move():
    if not stockfish:
        return jsonify({"error": "Stockfish non initialisé"}), 500

    if 'fen' not in session:
        return jsonify({"error": "Aucune partie en cours. Commencez une nouvelle partie."}), 400

    data = request.json
    move_uci = data.get('move') # e.g., "e2e4"

    # Reconstruire l'état du board python-chess (si utilisé)
    board = chess.Board(session['fen'])
    
    # Validation du tour
    current_player_color = 'w' if board.turn == chess.WHITE else 'b'
    if session['turn'] != current_player_color:
         return jsonify({"error": "Pas votre tour.", "fen": session['fen'], "turn": session['turn']}), 400

    try:
        move_obj = board.parse_uci(move_uci)
    except ValueError:
        return jsonify({"error": "Format de coup invalide.", "fen": session['fen'], "turn": session['turn']}), 400


    if not stockfish.is_move_correct(move_uci) or move_obj not in board.legal_moves:
        return jsonify({"error": "Coup illégal.", "fen": session['fen'], "turn": session['turn']}), 400

    # Appliquer le coup humain
    stockfish.make_moves_from_current_position([move_uci])
    board.push(move_obj)
    session['fen'] = stockfish.get_fen_position() # ou board.fen()
    session['history'].append(move_uci)
    session['turn'] = 'b' if current_player_color == 'w' else 'w'
    
    ai_move_uci = None
    game_status = "En cours"

    if board.is_checkmate():
        game_status = f"Mat! {'Les Blancs' if board.turn == chess.BLACK else 'Les Noirs'} gagnent."
    elif board.is_stalemate() or board.is_insufficient_material() or board.is_seventyfive_moves() or board.is_fivefold_repetition():
        game_status = "Pat!"
        
    # Mode IA
    if session['mode'] == 'ai' and game_status == "En cours" and ( (board.turn == chess.BLACK and current_player_color == 'w') or \
                                                                    (board.turn == chess.WHITE and current_player_color == 'b') ) : # Tour de l'IA
        # S'assurer que stockfish a la bonne position si on utilise board.fen()
        stockfish.set_fen_position(board.fen()) 
        ai_move_uci = stockfish.get_best_move_time(1000) # 1 seconde de réflexion
        if ai_move_uci:
            ai_move_obj = board.parse_uci(ai_move_uci)
            stockfish.make_moves_from_current_position([ai_move_uci]) # Stockfish est déjà à jour
            board.push(ai_move_obj)
            session['fen'] = stockfish.get_fen_position() # ou board.fen()
            session['history'].append(ai_move_uci)
            session['turn'] = 'w' if session['turn'] == 'b' else 'b'

            if board.is_checkmate():
                 game_status = f"Mat! {'Les Blancs' if board.turn == chess.BLACK else 'Les Noirs'} gagnent."
            elif board.is_stalemate() or board.is_insufficient_material() or board.is_seventyfive_moves() or board.is_fivefold_repetition():
                game_status = "Pat!"
        else: # Si l'IA ne retourne pas de coup (ce qui peut arriver si elle est matée/patée)
            if board.is_checkmate():
                 game_status = f"Mat! {'Les Blancs' if board.turn == chess.BLACK else 'Les Noirs'} gagnent."
            elif board.is_stalemate():
                game_status = "Pat!"


    return jsonify({
        "fen": session['fen'],
        "turn": session['turn'],
        "last_move_human": move_uci,
        "last_move_ai": ai_move_uci,
        "game_status": game_status,
        "history": session['history']
    })

if __name__ == '__main__':
    app.run(debug=True)