| |
| |
| """ |
| Jeu d'échecs + démineur — interface web Gradio (2 joueurs, tour par tour). |
| - Pièces: p (pion), f (fou), t (tour), c (cavalier), R (reine), k (roi) |
| MAJ = Blanc, minuscule = Noir |
| - Mines placées aléatoirement sur cases vides au début. |
| - Déplacement sur une mine -> pièce éliminée (mine explose). |
| - Cases sûres révélées comme en démineur (compte des mines adjacentes, cascade si 0). |
| - Règles de base : mouvements, captures, échec, échec-et-mat, promotion automatique. |
| - Castling & en passant non implémentés. |
| """ |
|
|
| import random |
| import copy |
| import gradio as gr |
|
|
| FILES = "abcdefgh" |
| RANKS = "12345678" |
|
|
| def sq_to_coords(sq): |
| sq = sq.lower() |
| return FILES.index(sq[0]), RANKS.index(sq[1]) |
|
|
| def coords_to_sq(x,y): |
| return FILES[x] + RANKS[y] |
|
|
| def in_bounds(x,y): |
| return 0 <= x < 8 and 0 <= y < 8 |
|
|
| |
| def initial_board(): |
| |
| board = [[None for _ in range(8)] for _ in range(8)] |
| |
| white_row = ['t','c','f','R','k','f','c','t'] |
| for x,p in enumerate(white_row): |
| board[x][0] = ('W', p) |
| for x in range(8): |
| board[x][1] = ('W', 'p') |
| |
| black_row = ['t','c','f','R','k','f','c','t'] |
| for x,p in enumerate(black_row): |
| board[x][7] = ('B', p) |
| for x in range(8): |
| board[x][6] = ('B', 'p') |
| return board |
|
|
| |
| def generate_mines(board, density=0.15): |
| empty = [(x,y) for x in range(8) for y in range(8) if board[x][y] is None] |
| n = max(1, int(len(empty) * density)) |
| mines = set(random.sample(empty, n)) |
| adj = {} |
| for x in range(8): |
| for y in range(8): |
| if (x,y) in mines: |
| adj[(x,y)] = -1 |
| else: |
| cnt = 0 |
| for dx in (-1,0,1): |
| for dy in (-1,0,1): |
| if dx==0 and dy==0: continue |
| nx,ny = x+dx, y+dy |
| if in_bounds(nx,ny) and (nx,ny) in mines: |
| cnt += 1 |
| adj[(x,y)] = cnt |
| revealed = set() |
| exploded = set() |
| return mines, revealed, adj, exploded |
|
|
| def reveal_cascade(revealed, adj, start): |
| stack = [start] |
| while stack: |
| s = stack.pop() |
| if s in revealed: |
| continue |
| revealed.add(s) |
| if adj.get(s,0) == 0: |
| x,y = s |
| for dx in (-1,0,1): |
| for dy in (-1,0,1): |
| nx,ny = x+dx, y+dy |
| if dx==0 and dy==0: continue |
| if in_bounds(nx,ny) and (nx,ny) not in revealed: |
| stack.append((nx,ny)) |
|
|
| |
| def piece_to_char(piece): |
| if piece is None: |
| return '.' |
| col,ptype = piece |
| ch = ptype |
| return ch.upper() if col=='W' else ch.lower() |
|
|
| def render_board(board, mines, revealed, adj, exploded): |
| lines = [] |
| lines.append(" a b c d e f g h") |
| lines.append(" -----------------") |
| for y in range(7,-1,-1): |
| row = f" {y+1} |" |
| for x in range(8): |
| if (x,y) in exploded: |
| cell = "X" |
| elif board[x][y] is not None: |
| cell = piece_to_char(board[x][y]) |
| elif (x,y) in revealed: |
| cnt = adj.get((x,y), 0) |
| cell = str(cnt) if cnt>0 else ' ' |
| else: |
| cell = '.' |
| row += ' ' + cell |
| row += f" | {y+1}" |
| lines.append(row) |
| lines.append(" -----------------") |
| lines.append(" a b c d e f g h") |
| return "\n".join(lines) |
|
|
| |
| DIRECTIONS_ROOK = [(1,0),(-1,0),(0,1),(0,-1)] |
| DIRECTIONS_BISHOP = [(1,1),(1,-1),(-1,1),(-1,-1)] |
| KNIGHT_MOVES = [(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)] |
|
|
| def generate_pseudo_legal_moves_from(board, x, y): |
| piece = board[x][y] |
| if piece is None: |
| return [] |
| color, ptype = piece |
| moves = [] |
| if ptype == 'p': |
| |
| diry = 1 if color=='W' else -1 |
| start_rank = 1 if color=='W' else 6 |
| |
| nx, ny = x, y + diry |
| if in_bounds(nx,ny) and board[nx][ny] is None: |
| moves.append((nx,ny)) |
| |
| nx2, ny2 = x, y + 2*diry |
| if y == start_rank and in_bounds(nx2,ny2) and board[nx2][ny2] is None: |
| moves.append((nx2,ny2)) |
| |
| for dx in (-1,1): |
| cx, cy = x+dx, y+diry |
| if in_bounds(cx,cy) and board[cx][cy] is not None and board[cx][cy][0] != color: |
| moves.append((cx,cy)) |
| elif ptype == 'c': |
| for dx,dy in KNIGHT_MOVES: |
| nx,ny = x+dx, y+dy |
| if in_bounds(nx,ny) and (board[nx][ny] is None or board[nx][ny][0] != color): |
| moves.append((nx,ny)) |
| elif ptype == 't': |
| for dx,dy in DIRECTIONS_ROOK: |
| nx,ny = x+dx, y+dy |
| while in_bounds(nx,ny): |
| if board[nx][ny] is None: |
| moves.append((nx,ny)) |
| else: |
| if board[nx][ny][0] != color: |
| moves.append((nx,ny)) |
| break |
| nx += dx; ny += dy |
| elif ptype == 'f': |
| for dx,dy in DIRECTIONS_BISHOP: |
| nx,ny = x+dx, y+dy |
| while in_bounds(nx,ny): |
| if board[nx][ny] is None: |
| moves.append((nx,ny)) |
| else: |
| if board[nx][ny][0] != color: |
| moves.append((nx,ny)) |
| break |
| nx += dx; ny += dy |
| elif ptype == 'R': |
| for dx,dy in DIRECTIONS_ROOK + DIRECTIONS_BISHOP: |
| nx,ny = x+dx, y+dy |
| while in_bounds(nx,ny): |
| if board[nx][ny] is None: |
| moves.append((nx,ny)) |
| else: |
| if board[nx][ny][0] != color: |
| moves.append((nx,ny)) |
| break |
| nx += dx; ny += dy |
| elif ptype == 'k': |
| for dx in (-1,0,1): |
| for dy in (-1,0,1): |
| if dx==0 and dy==0: continue |
| nx,ny = x+dx, y+dy |
| if in_bounds(nx,ny) and (board[nx][ny] is None or board[nx][ny][0] != color): |
| moves.append((nx,ny)) |
| return moves |
|
|
| def is_square_attacked(board, tx, ty, attacker_color): |
| for x in range(8): |
| for y in range(8): |
| p = board[x][y] |
| if p is not None and p[0] == attacker_color: |
| for (mx,my) in generate_pseudo_legal_moves_from(board, x, y): |
| if mx==tx and my==ty: |
| return True |
| return False |
|
|
| def locate_king(board, color): |
| for x in range(8): |
| for y in range(8): |
| p = board[x][y] |
| if p is not None and p[0]==color and p[1]=='k': |
| return (x,y) |
| return None |
|
|
| def king_in_check(board, color): |
| kpos = locate_king(board, color) |
| if kpos is None: |
| return True |
| return is_square_attacked(board, kpos[0], kpos[1], 'B' if color=='W' else 'W') |
|
|
| def all_legal_moves(board, color): |
| moves = [] |
| for x in range(8): |
| for y in range(8): |
| p = board[x][y] |
| if p is None or p[0]!=color: continue |
| for (nx,ny) in generate_pseudo_legal_moves_from(board, x, y): |
| b2 = copy.deepcopy(board) |
| b2[nx][ny] = b2[x][y] |
| b2[x][y] = None |
| |
| if not king_in_check(b2, color): |
| moves.append(((x,y),(nx,ny))) |
| return moves |
|
|
| |
| def apply_move(board, from_xy, to_xy, mines, revealed, adj, exploded): |
| fx,fy = from_xy; tx,ty = to_xy |
| piece = board[fx][fy] |
| if piece is None: |
| return board, False, False, False |
| |
| if (tx,ty) in mines: |
| |
| board[fx][fy] = None |
| exploded.add((tx,ty)) |
| mines.remove((tx,ty)) |
| revealed.add((tx,ty)) |
| return board, True, False, False |
| |
| capture = board[tx][ty] is not None |
| board[tx][ty] = board[fx][fy] |
| board[fx][fy] = None |
| |
| reveal_cascade(revealed, adj, (tx,ty)) |
| |
| promotion = False |
| col, ptype = board[tx][ty] |
| if ptype == 'p': |
| if (col=='W' and ty==7) or (col=='B' and ty==0): |
| board[tx][ty] = (col, 'R') |
| promotion = True |
| return board, False, capture, promotion |
|
|
| |
| def parse_move_input(s): |
| s = s.strip().lower().replace('-', ' ').replace('->',' ').replace(',', ' ') |
| parts = s.split() |
| if len(parts)==1 and len(parts[0])==4: |
| return parts[0][0:2], parts[0][2:4] |
| if len(parts)==2 and all(len(p)==2 for p in parts): |
| return parts[0], parts[1] |
| return None |
|
|
| |
| def new_game_state(density): |
| board = initial_board() |
| mines, revealed, adj, exploded = generate_mines(board, density=density) |
| state = { |
| "board": board, |
| "mines": mines, |
| "revealed": revealed, |
| "adj": adj, |
| "exploded": exploded, |
| "turn": 'W', |
| "move_number": 1, |
| "log": ["Nouvelle partie créée. Blanc commence."] |
| } |
| return state |
|
|
| |
| def start_new_game(density): |
| state = new_game_state(density) |
| board = state["board"]; mines=state["mines"]; revealed=state["revealed"]; adj=state["adj"]; exploded=state["exploded"] |
| board_text = render_board(board, mines, revealed, adj, exploded) |
| return board_text, "\n".join(state["log"]), state |
|
|
| def submit_move(move_str, state): |
| if state is None: |
| return "Aucune partie en cours.", "Aucune", None |
| board = state["board"]; mines=state["mines"]; revealed=state["revealed"]; adj=state["adj"]; exploded=state["exploded"] |
| turn = state["turn"] |
| log = state["log"] |
| move = parse_move_input(move_str or "") |
| if move is None: |
| log.append("Format invalide. Utilisez ex: e2e4") |
| return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state |
| from_sq, to_sq = move |
| try: |
| fx,fy = sq_to_coords(from_sq) |
| tx,ty = sq_to_coords(to_sq) |
| except Exception: |
| log.append("Coordonnées invalides.") |
| return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state |
| p = board[fx][fy] |
| if p is None or p[0] != turn: |
| log.append("Pas de pièce de votre couleur sur la case de départ.") |
| return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state |
| legal = all_legal_moves(board, turn) |
| ok = False |
| for (a,b),(c,d) in legal: |
| if a==fx and b==fy and c==tx and d==ty: |
| ok = True; break |
| if not ok: |
| log.append("Coup illégal ou qui laisserait le roi en échec.") |
| return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state |
| board, eliminated, capture, promotion = apply_move(board, (fx,fy), (tx,ty), mines, revealed, adj, exploded) |
| if eliminated: |
| log.append(f"BOOM ! Mine déclenchée en {to_sq}. Pièce éliminée.") |
| |
| if locate_king(board, turn) is None: |
| winner = 'Noir' if turn=='W' else 'Blanc' |
| log.append(f"Le roi de {'Blanc' if turn=='W' else 'Noir'} a été éliminé. {winner} gagne.") |
| return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state |
| else: |
| if capture: |
| log.append(f"Prise en {to_sq}.") |
| if promotion: |
| log.append(f"Promotion en Reine en {to_sq}.") |
| |
| state["turn"] = 'B' if turn=='W' else 'W' |
| state["move_number"] += 1 |
| |
| next_color = state["turn"] |
| if king_in_check(board, next_color): |
| |
| if not all_legal_moves(board, next_color): |
| winner = 'Blanc' if next_color=='B' else 'Noir' |
| log.append(f"Échec et mat ! {winner} gagne.") |
| else: |
| log.append(f"{'Blanc' if next_color=='W' else 'Noir'} est en échec.") |
| else: |
| if not all_legal_moves(board, next_color): |
| log.append("Pat (stalemate).") |
| state["log"] = log |
| return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state |
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("# ♟️ Échecs + Démineur (2 joueurs)") |
| gr.Markdown("Déplacez vos pièces normalement. Les cases vides initiales contiennent des mines aléatoires ; si une de vos pièces marche sur une mine, elle est éliminée.") |
| with gr.Row(): |
| density = gr.Slider(minimum=0.05, maximum=0.35, value=0.18, step=0.01, label="Densité des mines (fraction des cases vides)") |
| btn_new = gr.Button("Nouvelle partie") |
| board_area = gr.Textbox(label="Plateau", interactive=False, lines=12) |
| log_area = gr.Textbox(label="Journal de partie", interactive=False, lines=8) |
| move_in = gr.Textbox(label="Votre coup (ex: e2e4)", placeholder="e2e4", lines=1) |
| btn_move = gr.Button("Jouer le coup") |
|
|
| state = gr.State(None) |
|
|
| btn_new.click(fn=start_new_game, inputs=[density], outputs=[board_area, log_area, state]) |
| btn_move.click(fn=submit_move, inputs=[move_in, state], outputs=[board_area, log_area, state]) |
|
|
| gr.Markdown("**Règles simplifiées** : promotion automatique en reine, pas de roque, pas d'en-passant.") |
|
|
| |
| if __name__ == "__main__": |
| demo.launch() |
|
|