-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
53 lines (47 loc) · 1.92 KB
/
example.py
File metadata and controls
53 lines (47 loc) · 1.92 KB
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
# Helper Python code for mapping from an FEN chessboard representation string, to a python dictionary formatted for rendering in a Django template, similar to Sudoku.
def fen_to_dict(fen_string):
# Mapping of pieces to HTML entities
piece_to_html = {
'K': '♔', # White King
'Q': '♕', # White Queen
'R': '♖', # White Rook
'B': '♗', # White Bishop
'N': '♘', # White Knight
'P': '♙', # White Pawn
'k': '♚', # Black King
'q': '♛', # Black Queen
'r': '♜', # Black Rook
'b': '♝', # Black Bishop
'n': '♞', # Black Knight
'p': '♟', # Black Pawn
}
# Get the position part of the FEN string
position_part = fen_string.split(' ')[0]
ranks = position_part.split('/')
rows_list = []
for rank_index, rank_str in enumerate(ranks):
rank_number = 8 - rank_index # Rank numbers from 8 to 1
rank_dict = {}
file_index = 0 # Files from 'a' to 'h'
for c in rank_str:
if c.isdigit():
n = int(c)
for _ in range(n):
if file_index >= 8:
break # Safety check
file_letter = chr(ord('a') + file_index)
position = f"{file_letter}{rank_number}"
rank_dict[position] = ' '
file_index += 1
else:
if file_index >= 8:
break # Safety check
file_letter = chr(ord('a') + file_index)
position = f"{file_letter}{rank_number}"
rank_dict[position] = piece_to_html.get(c, ' ')
file_index += 1
rows_list.append(rank_dict)
return rows_list
# Example usage:
fen_string = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'
board_rows = fen_to_dict(fen_string)