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
+ """
3
+ Jeu d'échecs console 2 joueurs + mécanique démineur sur cases vides initiales.
4
+ - Pièces: p (pion), f (fou), t (tour), c (cavalier), R (reine), k (roi)
5
+ - MAJ = Blanc, minuscule = Noir
6
+ - Mines générées aléatoirement à l'initialisation sur les cases vides.
7
+ - Quand une pièce marche sur une mine -> la pièce est éliminée.
8
+ - Quand une pièce marche sur une case sûre -> la case est révélée et affiche le nombre
9
+ de mines adjacentes (cascade si 0).
10
+ - Règles de base : mouvements, captures, échec, échec-et-mat, promotion.
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
+ """ex: 'e4' -> (4, 4) where (file, rank) indices 0..7"""
24
+ file = FILES.index(sq[0])
25
+ rank = RANKS.index(sq[1])
26
+ return (file, rank)
27
+
28
+ def coords_to_sq(x, y):
29
+ return FILES[x] + RANKS[y]
30
+
31
+ def in_bounds(x, y):
32
+ return 0 <= x < 8 and 0 <= y < 8
33
+
34
+ # === Initial board setup (standard chess) ===
35
+ def initial_board():
36
+ # Empty board: None
37
+ board = [[None for _ in range(8)] for _ in range(8)]
38
+ # Place pieces: white at rank 1-2 (y=0..1), black at rank 7-8 (y=6..7) but we'll use rank indices 0..7 with 0='1'
39
+ # We'll map ranks: y=0 -> '1', y=7 -> '8' (consistent with coords_to_sq)
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) # white pieces uppercase display
44
+ for x in range(8):
45
+ board[x][1] = ('W', 'p') # pawns
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) # color 'B' but will display as lowercase
51
+ for x in range(8):
52
+ board[x][6] = ('B', 'p')
53
+
54
+ return board
55
+
56
+ # === Mines field and reveal map ===
57
+ def generate_mines(board, density=0.15):
58
+ """
59
+ board: current board 2D list with None or (color, piece)
60
+ density: fraction of empty squares to turn into mines (0..1)
61
+ Returns:
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
+ adj_counts[(x,y)] = -1
75
+ else:
76
+ cnt = 0
77
+ for dx in (-1,0,1):
78
+ for dy in (-1,0,1):
79
+ nx, ny = x+dx, y+dy
80
+ if (dx==0 and dy==0) or not in_bounds(nx,ny):
81
+ continue
82
+ if (nx,ny) in mines:
83
+ cnt += 1
84
+ adj_counts[(x,y)] = cnt
85
+ revealed = set()
86
+ exploded = set() # squares where a mine exploded
87
+ return mines, revealed, adj_counts, exploded
88
+
89
+ def reveal_cascade(revealed, adj_counts, start):
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 adj_counts.get(s, 0) == 0:
98
+ x,y = s
99
+ for dx in (-1,0,1):
100
+ for dy in (-1,0,1):
101
+ nx, ny = x+dx, y+dy
102
+ if (dx==0 and dy==0) or not in_bounds(nx,ny):
103
+ continue
104
+ if (nx,ny) not in revealed:
105
+ stack.append((nx,ny))
106
+
107
+ # === Display functions ===
108
+ def piece_to_char(piece):
109
+ # piece is (color, type) or None
110
+ if piece is None:
111
+ return '.'
112
+ color, ptype = piece
113
+ # ptype is one of p,f,t,c,R,k
114
+ # Display: White = uppercase letter, Black = lowercase
115
+ char = ptype
116
+ if color == 'W':
117
+ return char.upper()
118
+ else:
119
+ return char.lower()
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:
138
+ cell = "X"
139
+ elif board[x][y] is not None:
140
+ cell = piece_to_char(board[x][y])
141
+ elif (x,y) in revealed:
142
+ cnt = adj_counts.get((x,y), 0)
143
+ cell = str(cnt) if cnt>0 else ' '
144
+ else:
145
+ cell = '.'
146
+ row += ' ' + cell
147
+ row += f" | {y+1}"
148
+ rows.append(row)
149
+ rows.append(" -----------------")
150
+ rows.append(" a b c d e f g h")
151
+ return "\n".join(rows)
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 is_opponent(piece, color):
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': # pawn
207
+ if color == 'W':
208
+ forward = (0, 1)
209
+ start_rank = 1
210
+ dir_sign = 1
211
+ else:
212
+ forward = (0, -1)
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 steps from starting rank
220
+ if y == start_rank:
221
+ nx2, ny2 = x + forward[0]*2, y + forward[1]*2
222
+ if in_bounds(nx2, ny2) and board[nx2][ny2] is None:
223
+ moves.append((nx2, ny2))
224
+ # captures diagonally
225
+ for dx in (-1,1):
226
+ cx, cy = x+dx, y+forward[1]
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
+ # Note: en passant NOT implemented
230
+ elif ptype == 'c': # cavalier
231
+ for dx,dy in KNIGHT_MOVES:
232
+ nx, ny = x+dx, y+dy
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': # tour (rook)
236
+ for dx,dy in DIRECTIONS_ROOK:
237
+ nx, ny = x+dx, y+dy
238
+ while in_bounds(nx,ny):
239
+ if board[nx][ny] is None:
240
+ moves.append((nx,ny))
241
+ else:
242
+ if board[nx][ny][0] != color:
243
+ moves.append((nx,ny))
244
+ break
245
+ nx += dx; ny += dy
246
+ elif ptype == 'f': # fou (bishop)
247
+ for dx,dy in DIRECTIONS_BISHOP:
248
+ nx, ny = x+dx, y+dy
249
+ while in_bounds(nx,ny):
250
+ if board[nx][ny] is None:
251
+ moves.append((nx,ny))
252
+ else:
253
+ if board[nx][ny][0] != color:
254
+ moves.append((nx,ny))
255
+ break
256
+ nx += dx; ny += dy
257
+ elif ptype == 'R': # reine (queen)
258
+ for dx,dy in DIRECTIONS_ROOK + DIRECTIONS_BISHOP:
259
+ nx, ny = x+dx, y+dy
260
+ while in_bounds(nx,ny):
261
+ if board[nx][ny] is None:
262
+ moves.append((nx,ny))
263
+ else:
264
+ if board[nx][ny][0] != color:
265
+ moves.append((nx,ny))
266
+ break
267
+ nx += dx; ny += dy
268
+ elif ptype == 'k': # roi
269
+ for dx in (-1,0,1):
270
+ for dy in (-1,0,1):
271
+ if dx==0 and dy==0: continue
272
+ nx, ny = x+dx, y+dy
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]
284
+ if p is not None and p[0] == attacker_color:
285
+ for (mx,my) in generate_pseudo_legal_moves_from(board, x, y):
286
+ if mx==tx and my==ty:
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 # no king = in "check" (dead)
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
+ # === Game loop & move execution including mine logic ===
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
+ # Reveal the destination (safe)
346
+ reveal_cascade(revealed, adj_counts, (tx,ty))
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') # promote to queen (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:
366
+ return parts[0][0:2], parts[0][2:4]
367
+ if len(parts)==2 and all(len(p)==2 for p in parts):
368
+ return parts[0], parts[1]
369
+ return None
370
+
371
+ def main():
372
+ print("=== ÉCHECS + DÉMINEUR ===")
373
+ print("Règles simplifiées : castling/en passant non implémentés. Promotion automatique en reine.")
374
+ board = initial_board()
375
+ mines, revealed, adj_counts, exploded = generate_mines(board, density=0.18)
376
+ turn = 'W' # White starts
377
+ move_number = 1
378
+
379
+ while True:
380
+ print("\n" + render_board(board, mines, revealed, adj_counts, exploded))
381
+ if king_in_check(board, turn):
382
+ print(f"Tour {move_number} - {'Blanc' if turn=='W' else 'Noir'}: Votre roi est en échec !")
383
+ else:
384
+ print(f"Tour {move_number} - {'Blanc' if turn=='W' else 'Noir'} à jouer.")
385
+
386
+ legal = all_legal_moves(board, turn)
387
+ if not legal:
388
+ if king_in_check(board, turn):
389
+ print(f"Échec et mat ! {'Noir' if turn=='W' else 'Blanc'} gagne.")
390
+ else:
391
+ print("Pat (stalemate).")
392
+ break
393
+
394
+ print("Entrez votre coup (ex: e2e4 ou e7 e5) ou 'quit' pour abandonner.")
395
+ inp = input("> ").strip()
396
+ if inp.lower() in ('quit','exit','q'):
397
+ print(f"{'Blanc' if turn=='W' else 'Noir'} a abandonné. Fin du jeu.")
398
+ break
399
+
400
+ parsed = parse_move_input(inp)
401
+ if parsed is None:
402
+ print("Format invalide. Réessayez.")
403
+ continue
404
+ from_sq, to_sq = parsed
405
+ try:
406
+ fx,fy = sq_to_coords(from_sq)
407
+ tx,ty = sq_to_coords(to_sq)
408
+ except Exception:
409
+ print("Coordonnées invalides. Utilisez a1..h8.")
410
+ continue
411
+
412
+ # Validate that there's a piece of player's color at from_sq
413
+ p = board[fx][fy]
414
+ if p is None or p[0] != turn:
415
+ print("Pas de pièce de votre couleur sur la case de départ.")
416
+ continue
417
+
418
+ # Check move is among legal moves
419
+ move_ok = False
420
+ for (a,b),(c,d) in legal:
421
+ if a==fx and b==fy and c==tx and d==ty:
422
+ move_ok = True; break
423
+ if not move_ok:
424
+ print("Coup illégal ou qui laisserait votre roi en échec. Réessayez.")
425
+ continue
426
+
427
+ # Apply move
428
+ board, eliminated, capture, promotion = apply_move(board, (fx,fy), (tx,ty), mines, revealed, adj_counts, exploded, turn)
429
+ if eliminated:
430
+ print("BOOM ! Mine déclenchée. Votre pièce a été éliminée.")
431
+ # If it was a king that exploded we should detect loss
432
+ # We'll check if the player's king still exists
433
+ if locate_king(board, turn) is None:
434
+ print(f"Votre roi a été éliminé par une mine. {'Noir' if turn=='W' else 'Blanc'} gagne.")
435
+ break
436
+ else:
437
+ if capture:
438
+ print("Prise !")
439
+ if promotion:
440
+ print("Promotion automatique en Reine (R).")
441
+
442
+ # next turn
443
+ turn = 'B' if turn=='W' else 'W'
444
+ move_number += 1
445
+
446
+ if __name__ == "__main__":
447
+ main()