Update app.py
Browse files
app.py
CHANGED
|
@@ -1,137 +1,103 @@
|
|
| 1 |
#!/usr/bin/env python3
|
|
|
|
| 2 |
"""
|
| 3 |
-
Jeu d'échecs
|
| 4 |
- Pièces: p (pion), f (fou), t (tour), c (cavalier), R (reine), k (roi)
|
| 5 |
-
|
| 6 |
-
- Mines
|
| 7 |
-
-
|
| 8 |
-
-
|
| 9 |
-
|
| 10 |
-
-
|
| 11 |
-
- Castling et en passant non gérés pour simplifier.
|
| 12 |
"""
|
| 13 |
|
| 14 |
import random
|
| 15 |
import copy
|
| 16 |
-
|
| 17 |
-
# === Utilitaires de gestion du plateau ===
|
| 18 |
|
| 19 |
FILES = "abcdefgh"
|
| 20 |
RANKS = "12345678"
|
| 21 |
|
| 22 |
def sq_to_coords(sq):
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
rank = RANKS.index(sq[1])
|
| 26 |
-
return (file, rank)
|
| 27 |
|
| 28 |
-
def coords_to_sq(x,
|
| 29 |
return FILES[x] + RANKS[y]
|
| 30 |
|
| 31 |
-
def in_bounds(x,
|
| 32 |
return 0 <= x < 8 and 0 <= y < 8
|
| 33 |
|
| 34 |
-
#
|
| 35 |
def initial_board():
|
| 36 |
-
#
|
| 37 |
board = [[None for _ in range(8)] for _ in range(8)]
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
# White pieces (bottom, ranks 1 & 2 -> y=0 and y=1)
|
| 41 |
-
white_row = ['t','c','f','R','k','f','c','t'] # tour, cavalier, fou, reine, roi, ...
|
| 42 |
for x,p in enumerate(white_row):
|
| 43 |
-
board[x][0] = ('W', p)
|
| 44 |
for x in range(8):
|
| 45 |
-
board[x][1] = ('W', 'p')
|
| 46 |
-
|
| 47 |
-
# Black pieces (top, ranks 8 & 7 -> y=7 and y=6)
|
| 48 |
black_row = ['t','c','f','R','k','f','c','t']
|
| 49 |
for x,p in enumerate(black_row):
|
| 50 |
-
board[x][7] = ('B', p)
|
| 51 |
for x in range(8):
|
| 52 |
board[x][6] = ('B', 'p')
|
| 53 |
-
|
| 54 |
return board
|
| 55 |
|
| 56 |
-
#
|
| 57 |
def generate_mines(board, density=0.15):
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
mines: set of (x,y) coordinates with mines
|
| 63 |
-
revealed: set of (x,y) coordinates already revealed (initially empty)
|
| 64 |
-
adj_counts: dict (x,y) -> adjacent mine count
|
| 65 |
-
Mines only placed on squares that are empty at initialisation (no piece).
|
| 66 |
-
"""
|
| 67 |
-
empty_sqs = [(x,y) for x in range(8) for y in range(8) if board[x][y] is None]
|
| 68 |
-
count = max(1, int(len(empty_sqs) * density))
|
| 69 |
-
mines = set(random.sample(empty_sqs, count))
|
| 70 |
-
adj_counts = {}
|
| 71 |
for x in range(8):
|
| 72 |
for y in range(8):
|
| 73 |
if (x,y) in mines:
|
| 74 |
-
|
| 75 |
else:
|
| 76 |
cnt = 0
|
| 77 |
for dx in (-1,0,1):
|
| 78 |
for dy in (-1,0,1):
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
if (nx,ny) in mines:
|
| 83 |
cnt += 1
|
| 84 |
-
|
| 85 |
revealed = set()
|
| 86 |
-
exploded = set()
|
| 87 |
-
return mines, revealed,
|
| 88 |
|
| 89 |
-
def reveal_cascade(revealed,
|
| 90 |
-
"""Reveal start and cascade zeros recursively (like démineur)."""
|
| 91 |
stack = [start]
|
| 92 |
while stack:
|
| 93 |
s = stack.pop()
|
| 94 |
if s in revealed:
|
| 95 |
continue
|
| 96 |
revealed.add(s)
|
| 97 |
-
if
|
| 98 |
x,y = s
|
| 99 |
for dx in (-1,0,1):
|
| 100 |
for dy in (-1,0,1):
|
| 101 |
-
nx,
|
| 102 |
-
if
|
| 103 |
-
|
| 104 |
-
if (nx,ny) not in revealed:
|
| 105 |
stack.append((nx,ny))
|
| 106 |
|
| 107 |
-
#
|
| 108 |
def piece_to_char(piece):
|
| 109 |
-
# piece is (color, type) or None
|
| 110 |
if piece is None:
|
| 111 |
return '.'
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
def render_board(board, mines, revealed, adj_counts, exploded):
|
| 122 |
-
"""
|
| 123 |
-
Returns a printable multiline string representing the board.
|
| 124 |
-
- Shows coordinates.
|
| 125 |
-
- For squares:
|
| 126 |
-
- If occupied by piece -> display piece char
|
| 127 |
-
- Else if revealed -> display adj count digit (0..8 -> '0' shown as ' ')
|
| 128 |
-
- Else -> '.' (hidden)
|
| 129 |
-
- If exploded mine -> 'X'
|
| 130 |
-
"""
|
| 131 |
-
rows = []
|
| 132 |
-
rows.append(" a b c d e f g h")
|
| 133 |
-
rows.append(" -----------------")
|
| 134 |
-
for y in range(7, -1, -1):
|
| 135 |
row = f" {y+1} |"
|
| 136 |
for x in range(8):
|
| 137 |
if (x,y) in exploded:
|
|
@@ -139,102 +105,53 @@ def render_board(board, mines, revealed, adj_counts, exploded):
|
|
| 139 |
elif board[x][y] is not None:
|
| 140 |
cell = piece_to_char(board[x][y])
|
| 141 |
elif (x,y) in revealed:
|
| 142 |
-
cnt =
|
| 143 |
cell = str(cnt) if cnt>0 else ' '
|
| 144 |
else:
|
| 145 |
cell = '.'
|
| 146 |
row += ' ' + cell
|
| 147 |
row += f" | {y+1}"
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
return "\n".join(
|
| 152 |
-
|
| 153 |
-
# === Chess move generation & legality check (basic but robust) ===
|
| 154 |
|
|
|
|
| 155 |
DIRECTIONS_ROOK = [(1,0),(-1,0),(0,1),(0,-1)]
|
| 156 |
DIRECTIONS_BISHOP = [(1,1),(1,-1),(-1,1),(-1,-1)]
|
| 157 |
KNIGHT_MOVES = [(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)]
|
| 158 |
|
| 159 |
-
def
|
| 160 |
-
return piece is not None and piece[0] != color
|
| 161 |
-
|
| 162 |
-
def is_same_color(piece, color):
|
| 163 |
-
return piece is not None and piece[0] == color
|
| 164 |
-
|
| 165 |
-
def locate_king(board, color):
|
| 166 |
-
for x in range(8):
|
| 167 |
-
for y in range(8):
|
| 168 |
-
p = board[x][y]
|
| 169 |
-
if p is not None and p[0]==color and p[1]=='k':
|
| 170 |
-
return (x,y)
|
| 171 |
-
return None
|
| 172 |
-
|
| 173 |
-
def square_attacked(board, x, y, by_color, mines=None):
|
| 174 |
-
"""
|
| 175 |
-
Returns True if square (x,y) is attacked by any piece of by_color.
|
| 176 |
-
Mines do not affect attacks (they only trigger on moving onto them).
|
| 177 |
-
"""
|
| 178 |
-
# Pawns attack diagonally forward (white up the board y+1, black down y-1)
|
| 179 |
-
if by_color == 'W':
|
| 180 |
-
for dx in (-1,1):
|
| 181 |
-
nx, ny = x+dx, y-1 # careful: we used y index 0->rank1; white moves up (increasing y)
|
| 182 |
-
# Wait: In our coords mapping y=0 is rank1, y=7 is rank8.
|
| 183 |
-
# White moves from rank1 to rank8 -> increasing y. Pawns attack y+1
|
| 184 |
-
# fix: white pawns attack y+1
|
| 185 |
-
# We'll implement correctly:
|
| 186 |
-
# Pawns
|
| 187 |
-
if by_color == 'W':
|
| 188 |
-
for dx in (-1,1):
|
| 189 |
-
nx, ny = x+dx, y-1 # incorrect earlier; correct is ny = y-1? Let's reason:
|
| 190 |
-
# Our rendering uses y increasing upwards (y=0 is rank1). White pawns start at y=1 and move to y=7 (increasing).
|
| 191 |
-
# So white pawn attacks at y+1. So ny = y+1 when attacking square (x,y) from a pawn at (nx,ny).
|
| 192 |
-
# We need to check pawns located at (nx,ny) such that they can attack (x,y).
|
| 193 |
-
pass
|
| 194 |
-
|
| 195 |
-
# To avoid confusion, we will implement attack detection by scanning all opponent pieces and checking if they can move to (x,y)
|
| 196 |
-
def generate_pseudo_legal_moves_from(board, x, y, mines=None):
|
| 197 |
-
"""
|
| 198 |
-
Generate pseudo-legal moves (ignores checks) for piece at (x,y).
|
| 199 |
-
Returns list of target (tx,ty) coordinates.
|
| 200 |
-
"""
|
| 201 |
piece = board[x][y]
|
| 202 |
if piece is None:
|
| 203 |
return []
|
| 204 |
color, ptype = piece
|
| 205 |
moves = []
|
| 206 |
-
if ptype == 'p':
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
start_rank = 6
|
| 214 |
-
dir_sign = -1
|
| 215 |
-
# one step
|
| 216 |
-
nx, ny = x + forward[0], y + forward[1]
|
| 217 |
-
if in_bounds(nx, ny) and board[nx][ny] is None:
|
| 218 |
moves.append((nx,ny))
|
| 219 |
-
# two
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
# captures diagonally
|
| 225 |
for dx in (-1,1):
|
| 226 |
-
cx, cy = x+dx, y+
|
| 227 |
if in_bounds(cx,cy) and board[cx][cy] is not None and board[cx][cy][0] != color:
|
| 228 |
moves.append((cx,cy))
|
| 229 |
-
|
| 230 |
-
elif ptype == 'c': # cavalier
|
| 231 |
for dx,dy in KNIGHT_MOVES:
|
| 232 |
-
nx,
|
| 233 |
if in_bounds(nx,ny) and (board[nx][ny] is None or board[nx][ny][0] != color):
|
| 234 |
moves.append((nx,ny))
|
| 235 |
-
elif ptype == 't':
|
| 236 |
for dx,dy in DIRECTIONS_ROOK:
|
| 237 |
-
nx,
|
| 238 |
while in_bounds(nx,ny):
|
| 239 |
if board[nx][ny] is None:
|
| 240 |
moves.append((nx,ny))
|
|
@@ -243,9 +160,9 @@ def generate_pseudo_legal_moves_from(board, x, y, mines=None):
|
|
| 243 |
moves.append((nx,ny))
|
| 244 |
break
|
| 245 |
nx += dx; ny += dy
|
| 246 |
-
elif ptype == 'f':
|
| 247 |
for dx,dy in DIRECTIONS_BISHOP:
|
| 248 |
-
nx,
|
| 249 |
while in_bounds(nx,ny):
|
| 250 |
if board[nx][ny] is None:
|
| 251 |
moves.append((nx,ny))
|
|
@@ -254,9 +171,9 @@ def generate_pseudo_legal_moves_from(board, x, y, mines=None):
|
|
| 254 |
moves.append((nx,ny))
|
| 255 |
break
|
| 256 |
nx += dx; ny += dy
|
| 257 |
-
elif ptype == 'R':
|
| 258 |
for dx,dy in DIRECTIONS_ROOK + DIRECTIONS_BISHOP:
|
| 259 |
-
nx,
|
| 260 |
while in_bounds(nx,ny):
|
| 261 |
if board[nx][ny] is None:
|
| 262 |
moves.append((nx,ny))
|
|
@@ -265,19 +182,16 @@ def generate_pseudo_legal_moves_from(board, x, y, mines=None):
|
|
| 265 |
moves.append((nx,ny))
|
| 266 |
break
|
| 267 |
nx += dx; ny += dy
|
| 268 |
-
elif ptype == 'k':
|
| 269 |
for dx in (-1,0,1):
|
| 270 |
for dy in (-1,0,1):
|
| 271 |
if dx==0 and dy==0: continue
|
| 272 |
-
nx,
|
| 273 |
if in_bounds(nx,ny) and (board[nx][ny] is None or board[nx][ny][0] != color):
|
| 274 |
moves.append((nx,ny))
|
| 275 |
-
# Castling omitted in this version
|
| 276 |
return moves
|
| 277 |
|
| 278 |
def is_square_attacked(board, tx, ty, attacker_color):
|
| 279 |
-
"""Return True if (tx,ty) is attacked by attacker_color pieces."""
|
| 280 |
-
# naive: iterate all attacker_color pieces and see if any pseudo-legal move reaches (tx,ty)
|
| 281 |
for x in range(8):
|
| 282 |
for y in range(8):
|
| 283 |
p = board[x][y]
|
|
@@ -287,79 +201,66 @@ def is_square_attacked(board, tx, ty, attacker_color):
|
|
| 287 |
return True
|
| 288 |
return False
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
def king_in_check(board, color):
|
| 291 |
kpos = locate_king(board, color)
|
| 292 |
if kpos is None:
|
| 293 |
-
return True
|
| 294 |
return is_square_attacked(board, kpos[0], kpos[1], 'B' if color=='W' else 'W')
|
| 295 |
|
| 296 |
def all_legal_moves(board, color):
|
| 297 |
-
"""
|
| 298 |
-
Generate all legal moves (from,to) for color, filtering out moves that leave king in check.
|
| 299 |
-
Returns list of ((x,y),(nx,ny)) moves.
|
| 300 |
-
"""
|
| 301 |
moves = []
|
| 302 |
for x in range(8):
|
| 303 |
for y in range(8):
|
| 304 |
p = board[x][y]
|
| 305 |
-
if p is None or p[0]!=color:
|
| 306 |
-
continue
|
| 307 |
for (nx,ny) in generate_pseudo_legal_moves_from(board, x, y):
|
| 308 |
-
# simulate move
|
| 309 |
b2 = copy.deepcopy(board)
|
| 310 |
b2[nx][ny] = b2[x][y]
|
| 311 |
b2[x][y] = None
|
|
|
|
| 312 |
if not king_in_check(b2, color):
|
| 313 |
moves.append(((x,y),(nx,ny)))
|
| 314 |
return moves
|
| 315 |
|
| 316 |
-
#
|
| 317 |
-
|
| 318 |
-
def apply_move(board, from_xy, to_xy, mines, revealed, adj_counts, exploded, color):
|
| 319 |
-
"""
|
| 320 |
-
Executes a move from -> to.
|
| 321 |
-
Returns (board, moved_piece_was_eliminated(bool), capture(bool), promotion(bool))
|
| 322 |
-
If destination is mined, the moving piece is removed instead.
|
| 323 |
-
"""
|
| 324 |
fx,fy = from_xy; tx,ty = to_xy
|
| 325 |
piece = board[fx][fy]
|
| 326 |
if piece is None:
|
| 327 |
return board, False, False, False
|
| 328 |
-
|
| 329 |
-
# If moving onto a mine
|
| 330 |
if (tx,ty) in mines:
|
| 331 |
# piece eliminated
|
| 332 |
board[fx][fy] = None
|
| 333 |
exploded.add((tx,ty))
|
| 334 |
-
# The mine is now exploded and removed from mines set (can't explode again)
|
| 335 |
mines.remove((tx,ty))
|
| 336 |
-
# Reveal the exploded square and possibly neighbors (we reveal adjacent counts too)
|
| 337 |
revealed.add((tx,ty))
|
| 338 |
return board, True, False, False
|
| 339 |
-
|
| 340 |
-
# Normal move/capture
|
| 341 |
capture = board[tx][ty] is not None
|
| 342 |
board[tx][ty] = board[fx][fy]
|
| 343 |
board[fx][fy] = None
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
# Pawn promotion
|
| 349 |
promotion = False
|
| 350 |
col, ptype = board[tx][ty]
|
| 351 |
if ptype == 'p':
|
| 352 |
if (col=='W' and ty==7) or (col=='B' and ty==0):
|
| 353 |
-
board[tx][ty] = (col, 'R')
|
| 354 |
promotion = True
|
| 355 |
-
|
| 356 |
return board, False, capture, promotion
|
| 357 |
|
|
|
|
| 358 |
def parse_move_input(s):
|
| 359 |
-
"""
|
| 360 |
-
Accepts formats like: e2e4 or e2 e4 or e2-e4
|
| 361 |
-
Returns (from_sq,to_sq) strings or None if invalid
|
| 362 |
-
"""
|
| 363 |
s = s.strip().lower().replace('-', ' ').replace('->',' ').replace(',', ' ')
|
| 364 |
parts = s.split()
|
| 365 |
if len(parts)==1 and len(parts[0])==4:
|
|
@@ -368,80 +269,108 @@ def parse_move_input(s):
|
|
| 368 |
return parts[0], parts[1]
|
| 369 |
return None
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
print("Règles simplifiées : castling/en passant non implémentés. Promotion automatique en reine.")
|
| 374 |
board = initial_board()
|
| 375 |
-
mines, revealed,
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
#
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
else:
|
| 437 |
-
if
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
if __name__ == "__main__":
|
| 447 |
-
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
+
# coding: utf-8
|
| 3 |
"""
|
| 4 |
+
Jeu d'échecs + démineur — interface web Gradio (2 joueurs, tour par tour).
|
| 5 |
- Pièces: p (pion), f (fou), t (tour), c (cavalier), R (reine), k (roi)
|
| 6 |
+
MAJ = Blanc, minuscule = Noir
|
| 7 |
+
- Mines placées aléatoirement sur cases vides au début.
|
| 8 |
+
- Déplacement sur une mine -> pièce éliminée (mine explose).
|
| 9 |
+
- Cases sûres révélées comme en démineur (compte des mines adjacentes, cascade si 0).
|
| 10 |
+
- Règles de base : mouvements, captures, échec, échec-et-mat, promotion automatique.
|
| 11 |
+
- Castling & en passant non implémentés.
|
|
|
|
| 12 |
"""
|
| 13 |
|
| 14 |
import random
|
| 15 |
import copy
|
| 16 |
+
import gradio as gr
|
|
|
|
| 17 |
|
| 18 |
FILES = "abcdefgh"
|
| 19 |
RANKS = "12345678"
|
| 20 |
|
| 21 |
def sq_to_coords(sq):
|
| 22 |
+
sq = sq.lower()
|
| 23 |
+
return FILES.index(sq[0]), RANKS.index(sq[1])
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
def coords_to_sq(x,y):
|
| 26 |
return FILES[x] + RANKS[y]
|
| 27 |
|
| 28 |
+
def in_bounds(x,y):
|
| 29 |
return 0 <= x < 8 and 0 <= y < 8
|
| 30 |
|
| 31 |
+
# ---------- initial board ----------
|
| 32 |
def initial_board():
|
| 33 |
+
# board[x][y] with x file 0..7 (a..h), y rank 0..7 (1..8)
|
| 34 |
board = [[None for _ in range(8)] for _ in range(8)]
|
| 35 |
+
# White (bottom) y=0 (rank1) and y=1 (rank2)
|
| 36 |
+
white_row = ['t','c','f','R','k','f','c','t'] # types; will display uppercase for white
|
|
|
|
|
|
|
| 37 |
for x,p in enumerate(white_row):
|
| 38 |
+
board[x][0] = ('W', p)
|
| 39 |
for x in range(8):
|
| 40 |
+
board[x][1] = ('W', 'p')
|
| 41 |
+
# Black (top) y=7 (rank8) and y=6 (rank7)
|
|
|
|
| 42 |
black_row = ['t','c','f','R','k','f','c','t']
|
| 43 |
for x,p in enumerate(black_row):
|
| 44 |
+
board[x][7] = ('B', p)
|
| 45 |
for x in range(8):
|
| 46 |
board[x][6] = ('B', 'p')
|
|
|
|
| 47 |
return board
|
| 48 |
|
| 49 |
+
# ---------- mines and demineur mechanics ----------
|
| 50 |
def generate_mines(board, density=0.15):
|
| 51 |
+
empty = [(x,y) for x in range(8) for y in range(8) if board[x][y] is None]
|
| 52 |
+
n = max(1, int(len(empty) * density))
|
| 53 |
+
mines = set(random.sample(empty, n))
|
| 54 |
+
adj = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
for x in range(8):
|
| 56 |
for y in range(8):
|
| 57 |
if (x,y) in mines:
|
| 58 |
+
adj[(x,y)] = -1
|
| 59 |
else:
|
| 60 |
cnt = 0
|
| 61 |
for dx in (-1,0,1):
|
| 62 |
for dy in (-1,0,1):
|
| 63 |
+
if dx==0 and dy==0: continue
|
| 64 |
+
nx,ny = x+dx, y+dy
|
| 65 |
+
if in_bounds(nx,ny) and (nx,ny) in mines:
|
|
|
|
| 66 |
cnt += 1
|
| 67 |
+
adj[(x,y)] = cnt
|
| 68 |
revealed = set()
|
| 69 |
+
exploded = set()
|
| 70 |
+
return mines, revealed, adj, exploded
|
| 71 |
|
| 72 |
+
def reveal_cascade(revealed, adj, start):
|
|
|
|
| 73 |
stack = [start]
|
| 74 |
while stack:
|
| 75 |
s = stack.pop()
|
| 76 |
if s in revealed:
|
| 77 |
continue
|
| 78 |
revealed.add(s)
|
| 79 |
+
if adj.get(s,0) == 0:
|
| 80 |
x,y = s
|
| 81 |
for dx in (-1,0,1):
|
| 82 |
for dy in (-1,0,1):
|
| 83 |
+
nx,ny = x+dx, y+dy
|
| 84 |
+
if dx==0 and dy==0: continue
|
| 85 |
+
if in_bounds(nx,ny) and (nx,ny) not in revealed:
|
|
|
|
| 86 |
stack.append((nx,ny))
|
| 87 |
|
| 88 |
+
# ---------- display ----------
|
| 89 |
def piece_to_char(piece):
|
|
|
|
| 90 |
if piece is None:
|
| 91 |
return '.'
|
| 92 |
+
col,ptype = piece
|
| 93 |
+
ch = ptype
|
| 94 |
+
return ch.upper() if col=='W' else ch.lower()
|
| 95 |
+
|
| 96 |
+
def render_board(board, mines, revealed, adj, exploded):
|
| 97 |
+
lines = []
|
| 98 |
+
lines.append(" a b c d e f g h")
|
| 99 |
+
lines.append(" -----------------")
|
| 100 |
+
for y in range(7,-1,-1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
row = f" {y+1} |"
|
| 102 |
for x in range(8):
|
| 103 |
if (x,y) in exploded:
|
|
|
|
| 105 |
elif board[x][y] is not None:
|
| 106 |
cell = piece_to_char(board[x][y])
|
| 107 |
elif (x,y) in revealed:
|
| 108 |
+
cnt = adj.get((x,y), 0)
|
| 109 |
cell = str(cnt) if cnt>0 else ' '
|
| 110 |
else:
|
| 111 |
cell = '.'
|
| 112 |
row += ' ' + cell
|
| 113 |
row += f" | {y+1}"
|
| 114 |
+
lines.append(row)
|
| 115 |
+
lines.append(" -----------------")
|
| 116 |
+
lines.append(" a b c d e f g h")
|
| 117 |
+
return "\n".join(lines)
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
# ---------- moves generation ----------
|
| 120 |
DIRECTIONS_ROOK = [(1,0),(-1,0),(0,1),(0,-1)]
|
| 121 |
DIRECTIONS_BISHOP = [(1,1),(1,-1),(-1,1),(-1,-1)]
|
| 122 |
KNIGHT_MOVES = [(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)]
|
| 123 |
|
| 124 |
+
def generate_pseudo_legal_moves_from(board, x, y):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
piece = board[x][y]
|
| 126 |
if piece is None:
|
| 127 |
return []
|
| 128 |
color, ptype = piece
|
| 129 |
moves = []
|
| 130 |
+
if ptype == 'p':
|
| 131 |
+
# pawns: white moves up (y+1), black moves down (y-1)
|
| 132 |
+
diry = 1 if color=='W' else -1
|
| 133 |
+
start_rank = 1 if color=='W' else 6
|
| 134 |
+
# one forward
|
| 135 |
+
nx, ny = x, y + diry
|
| 136 |
+
if in_bounds(nx,ny) and board[nx][ny] is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
moves.append((nx,ny))
|
| 138 |
+
# two forward from start
|
| 139 |
+
nx2, ny2 = x, y + 2*diry
|
| 140 |
+
if y == start_rank and in_bounds(nx2,ny2) and board[nx2][ny2] is None:
|
| 141 |
+
moves.append((nx2,ny2))
|
| 142 |
+
# captures
|
|
|
|
| 143 |
for dx in (-1,1):
|
| 144 |
+
cx, cy = x+dx, y+diry
|
| 145 |
if in_bounds(cx,cy) and board[cx][cy] is not None and board[cx][cy][0] != color:
|
| 146 |
moves.append((cx,cy))
|
| 147 |
+
elif ptype == 'c':
|
|
|
|
| 148 |
for dx,dy in KNIGHT_MOVES:
|
| 149 |
+
nx,ny = x+dx, y+dy
|
| 150 |
if in_bounds(nx,ny) and (board[nx][ny] is None or board[nx][ny][0] != color):
|
| 151 |
moves.append((nx,ny))
|
| 152 |
+
elif ptype == 't':
|
| 153 |
for dx,dy in DIRECTIONS_ROOK:
|
| 154 |
+
nx,ny = x+dx, y+dy
|
| 155 |
while in_bounds(nx,ny):
|
| 156 |
if board[nx][ny] is None:
|
| 157 |
moves.append((nx,ny))
|
|
|
|
| 160 |
moves.append((nx,ny))
|
| 161 |
break
|
| 162 |
nx += dx; ny += dy
|
| 163 |
+
elif ptype == 'f':
|
| 164 |
for dx,dy in DIRECTIONS_BISHOP:
|
| 165 |
+
nx,ny = x+dx, y+dy
|
| 166 |
while in_bounds(nx,ny):
|
| 167 |
if board[nx][ny] is None:
|
| 168 |
moves.append((nx,ny))
|
|
|
|
| 171 |
moves.append((nx,ny))
|
| 172 |
break
|
| 173 |
nx += dx; ny += dy
|
| 174 |
+
elif ptype == 'R':
|
| 175 |
for dx,dy in DIRECTIONS_ROOK + DIRECTIONS_BISHOP:
|
| 176 |
+
nx,ny = x+dx, y+dy
|
| 177 |
while in_bounds(nx,ny):
|
| 178 |
if board[nx][ny] is None:
|
| 179 |
moves.append((nx,ny))
|
|
|
|
| 182 |
moves.append((nx,ny))
|
| 183 |
break
|
| 184 |
nx += dx; ny += dy
|
| 185 |
+
elif ptype == 'k':
|
| 186 |
for dx in (-1,0,1):
|
| 187 |
for dy in (-1,0,1):
|
| 188 |
if dx==0 and dy==0: continue
|
| 189 |
+
nx,ny = x+dx, y+dy
|
| 190 |
if in_bounds(nx,ny) and (board[nx][ny] is None or board[nx][ny][0] != color):
|
| 191 |
moves.append((nx,ny))
|
|
|
|
| 192 |
return moves
|
| 193 |
|
| 194 |
def is_square_attacked(board, tx, ty, attacker_color):
|
|
|
|
|
|
|
| 195 |
for x in range(8):
|
| 196 |
for y in range(8):
|
| 197 |
p = board[x][y]
|
|
|
|
| 201 |
return True
|
| 202 |
return False
|
| 203 |
|
| 204 |
+
def locate_king(board, color):
|
| 205 |
+
for x in range(8):
|
| 206 |
+
for y in range(8):
|
| 207 |
+
p = board[x][y]
|
| 208 |
+
if p is not None and p[0]==color and p[1]=='k':
|
| 209 |
+
return (x,y)
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
def king_in_check(board, color):
|
| 213 |
kpos = locate_king(board, color)
|
| 214 |
if kpos is None:
|
| 215 |
+
return True
|
| 216 |
return is_square_attacked(board, kpos[0], kpos[1], 'B' if color=='W' else 'W')
|
| 217 |
|
| 218 |
def all_legal_moves(board, color):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
moves = []
|
| 220 |
for x in range(8):
|
| 221 |
for y in range(8):
|
| 222 |
p = board[x][y]
|
| 223 |
+
if p is None or p[0]!=color: continue
|
|
|
|
| 224 |
for (nx,ny) in generate_pseudo_legal_moves_from(board, x, y):
|
|
|
|
| 225 |
b2 = copy.deepcopy(board)
|
| 226 |
b2[nx][ny] = b2[x][y]
|
| 227 |
b2[x][y] = None
|
| 228 |
+
# If move captures the opponent king by moving onto it, that's allowed but leads to win
|
| 229 |
if not king_in_check(b2, color):
|
| 230 |
moves.append(((x,y),(nx,ny)))
|
| 231 |
return moves
|
| 232 |
|
| 233 |
+
# ---------- apply move with mine logic ----------
|
| 234 |
+
def apply_move(board, from_xy, to_xy, mines, revealed, adj, exploded):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
fx,fy = from_xy; tx,ty = to_xy
|
| 236 |
piece = board[fx][fy]
|
| 237 |
if piece is None:
|
| 238 |
return board, False, False, False
|
| 239 |
+
# stepping onto mine?
|
|
|
|
| 240 |
if (tx,ty) in mines:
|
| 241 |
# piece eliminated
|
| 242 |
board[fx][fy] = None
|
| 243 |
exploded.add((tx,ty))
|
|
|
|
| 244 |
mines.remove((tx,ty))
|
|
|
|
| 245 |
revealed.add((tx,ty))
|
| 246 |
return board, True, False, False
|
| 247 |
+
# normal move
|
|
|
|
| 248 |
capture = board[tx][ty] is not None
|
| 249 |
board[tx][ty] = board[fx][fy]
|
| 250 |
board[fx][fy] = None
|
| 251 |
+
# reveal
|
| 252 |
+
reveal_cascade(revealed, adj, (tx,ty))
|
| 253 |
+
# promotion
|
|
|
|
|
|
|
| 254 |
promotion = False
|
| 255 |
col, ptype = board[tx][ty]
|
| 256 |
if ptype == 'p':
|
| 257 |
if (col=='W' and ty==7) or (col=='B' and ty==0):
|
| 258 |
+
board[tx][ty] = (col, 'R')
|
| 259 |
promotion = True
|
|
|
|
| 260 |
return board, False, capture, promotion
|
| 261 |
|
| 262 |
+
# ---------- parsing ----------
|
| 263 |
def parse_move_input(s):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
s = s.strip().lower().replace('-', ' ').replace('->',' ').replace(',', ' ')
|
| 265 |
parts = s.split()
|
| 266 |
if len(parts)==1 and len(parts[0])==4:
|
|
|
|
| 269 |
return parts[0], parts[1]
|
| 270 |
return None
|
| 271 |
|
| 272 |
+
# ---------- Gradio app state helpers ----------
|
| 273 |
+
def new_game_state(density):
|
|
|
|
| 274 |
board = initial_board()
|
| 275 |
+
mines, revealed, adj, exploded = generate_mines(board, density=density)
|
| 276 |
+
state = {
|
| 277 |
+
"board": board,
|
| 278 |
+
"mines": mines,
|
| 279 |
+
"revealed": revealed,
|
| 280 |
+
"adj": adj,
|
| 281 |
+
"exploded": exploded,
|
| 282 |
+
"turn": 'W',
|
| 283 |
+
"move_number": 1,
|
| 284 |
+
"log": ["Nouvelle partie créée. Blanc commence."]
|
| 285 |
+
}
|
| 286 |
+
return state
|
| 287 |
+
|
| 288 |
+
# ---------- Gradio callbacks ----------
|
| 289 |
+
def start_new_game(density):
|
| 290 |
+
state = new_game_state(density)
|
| 291 |
+
board = state["board"]; mines=state["mines"]; revealed=state["revealed"]; adj=state["adj"]; exploded=state["exploded"]
|
| 292 |
+
board_text = render_board(board, mines, revealed, adj, exploded)
|
| 293 |
+
return board_text, "\n".join(state["log"]), state
|
| 294 |
+
|
| 295 |
+
def submit_move(move_str, state):
|
| 296 |
+
if state is None:
|
| 297 |
+
return "Aucune partie en cours.", "Aucune", None
|
| 298 |
+
board = state["board"]; mines=state["mines"]; revealed=state["revealed"]; adj=state["adj"]; exploded=state["exploded"]
|
| 299 |
+
turn = state["turn"]
|
| 300 |
+
log = state["log"]
|
| 301 |
+
move = parse_move_input(move_str or "")
|
| 302 |
+
if move is None:
|
| 303 |
+
log.append("Format invalide. Utilisez ex: e2e4")
|
| 304 |
+
return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state
|
| 305 |
+
from_sq, to_sq = move
|
| 306 |
+
try:
|
| 307 |
+
fx,fy = sq_to_coords(from_sq)
|
| 308 |
+
tx,ty = sq_to_coords(to_sq)
|
| 309 |
+
except Exception:
|
| 310 |
+
log.append("Coordonnées invalides.")
|
| 311 |
+
return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state
|
| 312 |
+
p = board[fx][fy]
|
| 313 |
+
if p is None or p[0] != turn:
|
| 314 |
+
log.append("Pas de pièce de votre couleur sur la case de départ.")
|
| 315 |
+
return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state
|
| 316 |
+
legal = all_legal_moves(board, turn)
|
| 317 |
+
ok = False
|
| 318 |
+
for (a,b),(c,d) in legal:
|
| 319 |
+
if a==fx and b==fy and c==tx and d==ty:
|
| 320 |
+
ok = True; break
|
| 321 |
+
if not ok:
|
| 322 |
+
log.append("Coup illégal ou qui laisserait le roi en échec.")
|
| 323 |
+
return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state
|
| 324 |
+
board, eliminated, capture, promotion = apply_move(board, (fx,fy), (tx,ty), mines, revealed, adj, exploded)
|
| 325 |
+
if eliminated:
|
| 326 |
+
log.append(f"BOOM ! Mine déclenchée en {to_sq}. Pièce éliminée.")
|
| 327 |
+
# check if king remains
|
| 328 |
+
if locate_king(board, turn) is None:
|
| 329 |
+
winner = 'Noir' if turn=='W' else 'Blanc'
|
| 330 |
+
log.append(f"Le roi de {'Blanc' if turn=='W' else 'Noir'} a été éliminé. {winner} gagne.")
|
| 331 |
+
return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state
|
| 332 |
+
else:
|
| 333 |
+
if capture:
|
| 334 |
+
log.append(f"Prise en {to_sq}.")
|
| 335 |
+
if promotion:
|
| 336 |
+
log.append(f"Promotion en Reine en {to_sq}.")
|
| 337 |
+
# switch turn
|
| 338 |
+
state["turn"] = 'B' if turn=='W' else 'W'
|
| 339 |
+
state["move_number"] += 1
|
| 340 |
+
# check for check/checkmate/stalemate
|
| 341 |
+
next_color = state["turn"]
|
| 342 |
+
if king_in_check(board, next_color):
|
| 343 |
+
# check if has legal moves
|
| 344 |
+
if not all_legal_moves(board, next_color):
|
| 345 |
+
winner = 'Blanc' if next_color=='B' else 'Noir'
|
| 346 |
+
log.append(f"Échec et mat ! {winner} gagne.")
|
| 347 |
else:
|
| 348 |
+
log.append(f"{'Blanc' if next_color=='W' else 'Noir'} est en échec.")
|
| 349 |
+
else:
|
| 350 |
+
if not all_legal_moves(board, next_color):
|
| 351 |
+
log.append("Pat (stalemate).")
|
| 352 |
+
state["log"] = log
|
| 353 |
+
return render_board(board,mines,revealed,adj,exploded), "\n".join(log), state
|
| 354 |
+
|
| 355 |
+
# ---------- Gradio UI ----------
|
| 356 |
+
with gr.Blocks() as demo:
|
| 357 |
+
gr.Markdown("# ♟️ Échecs + Démineur (2 joueurs)")
|
| 358 |
+
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.")
|
| 359 |
+
with gr.Row():
|
| 360 |
+
density = gr.Slider(minimum=0.05, maximum=0.35, value=0.18, step=0.01, label="Densité des mines (fraction des cases vides)")
|
| 361 |
+
btn_new = gr.Button("Nouvelle partie")
|
| 362 |
+
board_area = gr.Textbox(label="Plateau", interactive=False, lines=12)
|
| 363 |
+
log_area = gr.Textbox(label="Journal de partie", interactive=False, lines=8)
|
| 364 |
+
move_in = gr.Textbox(label="Votre coup (ex: e2e4)", placeholder="e2e4", lines=1)
|
| 365 |
+
btn_move = gr.Button("Jouer le coup")
|
| 366 |
+
|
| 367 |
+
state = gr.State(None)
|
| 368 |
+
|
| 369 |
+
btn_new.click(fn=start_new_game, inputs=[density], outputs=[board_area, log_area, state])
|
| 370 |
+
btn_move.click(fn=submit_move, inputs=[move_in, state], outputs=[board_area, log_area, state])
|
| 371 |
+
|
| 372 |
+
gr.Markdown("**Règles simplifiées** : promotion automatique en reine, pas de roque, pas d'en-passant.")
|
| 373 |
+
|
| 374 |
+
# Launch app
|
| 375 |
if __name__ == "__main__":
|
| 376 |
+
demo.launch()
|