File size: 3,935 Bytes
37d841f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec62aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d841f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import chess
import chess.pgn

# Mapeo de piezas: español → inglés
_PIECE_MAP = {'T': 'R', 'C': 'N', 'A': 'B', 'D': 'Q', 'R': 'K'}
_PROMO_MAP = {'T': 'R', 'C': 'N', 'A': 'B', 'D': 'Q'}


def translate_move(move_es: str) -> str:
    """Traduce una jugada de notacion espanola a notacion inglesa (SAN)."""
    if not move_es:
        return move_es
    # Enroque igual en ambos idiomas
    if move_es in ('O-O-O', 'O-O', '0-0-0', '0-0'):
        return move_es

    result = move_es
    # Promocion: =T → =R, =C → =N, etc. (antes de traducir piezas para evitar conflictos)
    result = re.sub(r'=([TCAD])', lambda m: '=' + _PROMO_MAP.get(m.group(1), m.group(1)), result)
    # Pieza al inicio: Cf3 → Nf3, Axc4 → Bxc4, Td1 → Rd1
    result = re.sub(r'^([TCADR])', lambda m: _PIECE_MAP.get(m.group(1), m.group(1)), result)
    return result


# Mapeo inverso inglés → español (para mostrar la mejor jugada de Stockfish,
# que viene en SAN inglés, dentro de comentarios en español).
_PIECE_MAP_EN_ES = {'R': 'T', 'N': 'C', 'B': 'A', 'Q': 'D', 'K': 'R'}
_PROMO_MAP_EN_ES = {'R': 'T', 'N': 'C', 'B': 'A', 'Q': 'D'}


def translate_move_en_es(move_en: str) -> str:
    """Traduce una jugada de notacion inglesa (SAN) a notacion espanola."""
    if not move_en:
        return move_en
    if move_en in ('O-O-O', 'O-O', '0-0-0', '0-0'):
        return move_en
    result = move_en
    result = re.sub(r'=([RNBQ])', lambda m: '=' + _PROMO_MAP_EN_ES.get(m.group(1), m.group(1)), result)
    result = re.sub(r'^([RNBQK])', lambda m: _PIECE_MAP_EN_ES.get(m.group(1), m.group(1)), result)
    return result


def _strip_annotations(san: str) -> str:
    return re.sub(r'[+#!?]', '', san).strip()


def validate_moves(moves_es: list[dict]) -> dict:
    """
    Valida la lista de jugadas con python-chess y construye el PGN en ingles.

    Entrada:
      moves_es: [{'number': 1, 'white': 'e4', 'black': 'c5'}, ...]

    Salida:
      {
        'pgn_en':           str   — movimientos validos hasta el primer error,
        'errors':           list  — todas las jugadas ilegales detectadas,
        'is_valid':         bool  — True si no hay errores,
        'valid_moves_count': int  — cantidad de medias jugadas validas,
      }
    """
    board      = chess.Board()
    errors     = []
    valid_sans = []
    stop       = False  # tras el primer error de legalidad, el tablero se desfasa y todo lo demas seria falso positivo

    for entry in moves_es:
        if stop:
            break
        n = entry.get('number', '?')
        for color, key in [('white', 'white'), ('black', 'black')]:
            move_es = entry.get(key, '').strip()
            if not move_es:
                continue

            move_en    = translate_move(move_es)
            move_clean = _strip_annotations(move_en)

            try:
                move = board.parse_san(move_clean)
                board.push(move)
                valid_sans.append(move_en)
            except (chess.IllegalMoveError, chess.AmbiguousMoveError, ValueError) as e:
                errors.append({
                    'number':  n,
                    'color':   color,
                    'move_es': move_es,
                    'move_en': move_en,
                    'reason':  str(e),
                })
                stop = True
                break

    # Construir solo la linea de movimientos (sin headers de PGN)
    tmp       = chess.Board()
    moves_pgn = []
    for i, san in enumerate(valid_sans):
        move = tmp.parse_san(_strip_annotations(san))
        tmp.push(move)
        if i % 2 == 0:
            moves_pgn.append(f"{i // 2 + 1}. {san}")
        else:
            moves_pgn[-1] += f" {san}"

    pgn_en = " ".join(moves_pgn)

    return {
        'pgn_en':            pgn_en,
        'errors':            errors,
        'is_valid':          len(errors) == 0,
        'valid_moves_count': len(valid_sans),
    }