darkmaria / app.py
Docfile's picture
Update app.py
dfaf016 verified
raw
history blame
6.15 kB
from flask import Flask, render_template, request, jsonify, session
from stockfish import Stockfish
import uuid
import json
app = Flask(__name__)
app.secret_key = 'your-secret-key-change-this'
# Configuration Stockfish
STOCKFISH_PATH = "/usr/games/stockfish" # Ajustez selon votre installation
# Stockage des parties en cours (en production, utilisez une base de données)
games = {}
class ChessGame:
def __init__(self, game_id, mode="human"):
self.game_id = game_id
self.mode = mode # "human" ou "ai"
self.current_player = "white"
self.moves_history = []
self.game_over = False
self.winner = None
# Initialiser Stockfish pour le mode AI
if mode == "ai":
try:
self.stockfish = Stockfish(path=STOCKFISH_PATH)
self.stockfish.set_depth(10)
except:
# Fallback si Stockfish n'est pas trouvé
self.stockfish = None
print("Attention: Stockfish non trouvé, mode AI désactivé")
else:
self.stockfish = None
# Position de départ FEN
self.fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
if self.stockfish:
self.stockfish.set_fen_position(self.fen)
def make_move(self, move):
"""Effectuer un coup"""
if self.game_over:
return False, "La partie est terminée"
if self.stockfish:
# Vérifier si le coup est légal
legal_moves = self.stockfish.get_legal_moves()
if move not in legal_moves:
return False, "Coup illégal"
# Effectuer le coup
self.stockfish.make_moves_from_current_position([move])
self.fen = self.stockfish.get_fen_position()
# Vérifier fin de partie
if self.stockfish.is_game_over():
self.game_over = True
if self.stockfish.is_checkmate():
self.winner = self.current_player
else:
self.winner = "draw"
else:
# Mode basique sans validation (pour le mode humain sans Stockfish)
pass
self.moves_history.append(move)
self.current_player = "black" if self.current_player == "white" else "white"
return True, "Coup effectué"
def get_ai_move(self):
"""Obtenir le coup de l'IA"""
if not self.stockfish or self.current_player != "black":
return None
best_move = self.stockfish.get_best_move()
return best_move
def get_legal_moves(self):
"""Obtenir les coups légaux"""
if self.stockfish:
return self.stockfish.get_legal_moves()
return []
def get_game_state(self):
"""Obtenir l'état complet du jeu"""
return {
"game_id": self.game_id,
"mode": self.mode,
"current_player": self.current_player,
"fen": self.fen,
"moves_history": self.moves_history,
"game_over": self.game_over,
"winner": self.winner,
"legal_moves": self.get_legal_moves()
}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/new_game', methods=['POST'])
def new_game():
"""Créer une nouvelle partie"""
data = request.json
mode = data.get('mode', 'human') # 'human' ou 'ai'
game_id = str(uuid.uuid4())
game = ChessGame(game_id, mode)
games[game_id] = game
# Stocker l'ID de partie dans la session
session['game_id'] = game_id
return jsonify({
"success": True,
"game_state": game.get_game_state()
})
@app.route('/api/make_move', methods=['POST'])
def make_move():
"""Effectuer un coup"""
data = request.json
game_id = session.get('game_id')
move = data.get('move')
if not game_id or game_id not in games:
return jsonify({"success": False, "error": "Partie non trouvée"})
game = games[game_id]
success, message = game.make_move(move)
if not success:
return jsonify({"success": False, "error": message})
response_data = {
"success": True,
"game_state": game.get_game_state()
}
# Si c'est le mode AI et c'est au tour de l'IA
if game.mode == "ai" and game.current_player == "black" and not game.game_over:
ai_move = game.get_ai_move()
if ai_move:
game.make_move(ai_move)
response_data["ai_move"] = ai_move
response_data["game_state"] = game.get_game_state()
return jsonify(response_data)
@app.route('/api/game_state', methods=['GET'])
def get_game_state():
"""Obtenir l'état actuel du jeu"""
game_id = session.get('game_id')
if not game_id or game_id not in games:
return jsonify({"success": False, "error": "Partie non trouvée"})
game = games[game_id]
return jsonify({
"success": True,
"game_state": game.get_game_state()
})
@app.route('/api/legal_moves', methods=['GET'])
def get_legal_moves():
"""Obtenir les coups légaux pour la position actuelle"""
game_id = session.get('game_id')
if not game_id or game_id not in games:
return jsonify({"success": False, "error": "Partie non trouvée"})
game = games[game_id]
return jsonify({
"success": True,
"legal_moves": game.get_legal_moves()
})
@app.route('/api/reset_game', methods=['POST'])
def reset_game():
"""Réinitialiser la partie actuelle"""
game_id = session.get('game_id')
if game_id and game_id in games:
mode = games[game_id].mode
games[game_id] = ChessGame(game_id, mode)
return jsonify({
"success": True,
"game_state": games[game_id].get_game_state()
})
return jsonify({"success": False, "error": "Partie non trouvée"})
if __name__ == '__main__':
app.run(debug=True)