File size: 13,650 Bytes
c86bbfa
d3e9649
c86bbfa
 
 
 
 
 
 
a334a38
c86bbfa
d3e9649
 
 
 
c86bbfa
 
 
 
 
fd01e53
 
c86bbfa
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e9649
 
 
 
 
 
 
 
c86bbfa
 
 
 
 
 
d3e9649
 
 
 
 
 
 
 
 
 
 
 
 
c86bbfa
a334a38
 
 
 
c86bbfa
 
 
 
 
 
 
 
fd01e53
c86bbfa
 
 
 
 
 
fd01e53
 
c86bbfa
fd01e53
c86bbfa
 
 
 
 
 
 
d3e9649
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c86bbfa
 
d3e9649
 
 
 
c86bbfa
 
 
 
 
 
 
 
 
d3e9649
 
 
c86bbfa
d3e9649
c86bbfa
 
 
 
 
 
d3e9649
c86bbfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e9649
c86bbfa
 
 
d3e9649
 
 
 
 
c86bbfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e9649
 
 
c86bbfa
 
 
 
 
 
 
 
d3e9649
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c86bbfa
d3e9649
c86bbfa
 
 
d3e9649
c86bbfa
 
 
 
 
d3e9649
 
 
 
 
 
c86bbfa
 
 
 
d3e9649
c86bbfa
 
 
 
 
d3e9649
c86bbfa
 
 
 
 
 
 
 
 
d3e9649
c86bbfa
d3e9649
 
 
 
 
 
 
 
 
 
 
c86bbfa
 
 
d3e9649
c86bbfa
 
 
 
 
 
 
d3e9649
c86bbfa
d3e9649
c86bbfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e9649
 
c86bbfa
 
 
 
 
 
 
d3e9649
 
 
 
 
 
c86bbfa
 
 
 
 
d3e9649
c86bbfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e9649
 
 
 
 
 
 
 
 
 
 
a334a38
d3e9649
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import io
import random

import chess
import chess.pgn
import chess.svg
import streamlit as st
from datasets import load_dataset

st.set_page_config(page_title="Chess Openings", page_icon="♖")

# Load external CSS
with open("style.css") as f:
    st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)


@st.cache_data
def load_data():
    ds = load_dataset("Lichess/chess-openings", split="train")
    df = ds.to_pandas()
    print(f"Total openings: {len(df)}")
    print(df["pgn"].head())
    return df


# Initialize session state variables
if "move_index" not in st.session_state:
    st.session_state.move_index = 0
if "user_move" not in st.session_state:
    st.session_state.user_move = ""
if "current_opening" not in st.session_state:
    st.session_state.current_opening = None
if "board" not in st.session_state:
    st.session_state.board = chess.Board()
if "moves" not in st.session_state:
    st.session_state.moves = []
if "final_move_completed" not in st.session_state:
    st.session_state.final_move_completed = False
if "random_opening" not in st.session_state:
    st.session_state.random_opening = None
if "completed_openings" not in st.session_state:
    st.session_state.completed_openings = set()
if "score" not in st.session_state:
    st.session_state.score = 0

data = load_data()
if data.empty:
    st.error("No data available. Failed to load from Hugging Face dataset.")
    st.stop()


def update_score():
    # Note: keeping it as a function to be able to try different scores
    st.session_state.score += 1
    #  score = 0
    # for opening in st.session_state.completed_openings:
    #     opening_data = data[data["name"] == opening].iloc[0]
    #     moves_count = opening_data["pgn"].count(".")
    #     score += moves_count

    # return score


# App layout
# st.markdown(
#     "<h1 style='text-align: center; font-size: 32px; margin-bottom: 10px; margin-top: -25px; padding-top: 0; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);'>Practice Chess Openings</h1>",
#     unsafe_allow_html=True,
# )

with st.sidebar:
    st.header("Settings")

    # Move range slider
    min_moves, max_moves = st.slider(
        "Select range of moves:", min_value=1, max_value=18, value=(1, 18), step=1
    )
    print(f"{min_moves=}, {max_moves=}")

    # Hide next moves checkbox
    hide_next_moves = st.checkbox("Hide next moves", value=True)

    # Filter the data based on the min and max number of moves
    filtered_data = data[
        (data["pgn"].str.count("\.") >= min_moves)
        & (data["pgn"].str.count("\.") <= max_moves)
    ]
    print(f"Total openings after filtering: {len(filtered_data)}")

    if filtered_data.empty:
        st.error(
            "No openings found with the specified number of moves. Please adjust your selection."
        )
        st.stop()

    # Random Opening button with custom styling
    random_button = st.button(
        "Random Opening",
        key="random_opening_button",
        use_container_width=True,
        help="Select a random opening",
        type="primary",  # This will give it a filled style
    )

    # Remove the previous CSS styling attempt
    # The CSS is now loaded from the external file

    if random_button:
        available_openings = [
            opening
            for opening in filtered_data["name"].unique()
            if opening not in st.session_state.completed_openings
        ]
        if available_openings:
            st.session_state.random_opening = random.choice(available_openings)
        else:
            st.warning(
                "You've completed all available openings! Resetting completed list."
            )
            st.session_state.completed_openings.clear()
            st.session_state.random_opening = random.choice(
                list(filtered_data["name"].unique())
            )
        st.rerun()

    # Check if the random_opening is still in the filtered data
    unique_openings = list(filtered_data["name"].unique())
    if st.session_state.random_opening not in unique_openings:
        st.session_state.random_opening = None

    opening = st.selectbox(
        label="Select an opening",
        options=unique_openings,
        index=unique_openings.index(st.session_state.random_opening)
        if st.session_state.random_opening
        else 0,
        key="opening_selector",
        placeholder="Select an opening",
    )

    if opening and opening != st.session_state.current_opening:
        st.session_state.current_opening = opening
        st.session_state.move_index = 0
        st.session_state.user_move = ""
        st.session_state.board = chess.Board()
        st.session_state.final_move_completed = False
        if "success_message" in st.session_state:
            del st.session_state.success_message

        # Get PGN for the selected opening and parse it
        selected_opening = filtered_data[filtered_data["name"] == opening].iloc[0]
        pgn = selected_opening["pgn"]
        game = chess.pgn.read_game(io.StringIO(pgn))
        st.session_state.moves = list(game.mainline_moves())

    with st.expander("Instructions"):
        st.write("This app lets you practice ~3500 chess openings.")
        st.write("Entering moves:")
        st.write("Use standard algebraic notation (SAN)")
        st.write("Examples: e4, Nf3, O-O (castling), exd5 (pawn capture)")
        st.write("Specify the piece (except for pawns) + destination square")
        st.write("Use 'x' for captures, '+' for check, '#' for checkmate")

        st.write("\nPiece symbols:")
        col1, col2, col3 = st.columns(3)
        with col1:
            st.write("♔ King (K)")
            st.write("♕ Queen (Q)")
        with col2:
            st.write("♖ Rook (R)")
            st.write("♗ Bishop (B)")
        with col3:
            st.write("♘ Knight (N)")
            st.write("♙ Pawn (no letter)")

        st.write(
            "See full notation [here](https://en.wikipedia.org/wiki/Algebraic_notation_(chess))"
        )
        st.write("---")
        st.write(
            "This app is using the [Lichess](https://lichess.org/) openings dataset via [HuggingFace](https://huggingface.co/datasets/Lichess/chess-openings)"
        )
        st.write(
            "This is just a toy app. Go to [Lichess](https://lichess.org/) \
            or [Chess.com](https://chess.com) for serious chess practice \
            (although I think this functionality isn't available there)"
        )


def update_board():
    st.session_state.board = chess.Board()
    for move in st.session_state.moves[: st.session_state.move_index]:
        st.session_state.board.push(move)


def update_next_move():
    if st.session_state.move_index < len(st.session_state.moves):
        st.session_state.move_index += 1
        update_board()


def update_prev_move():
    if st.session_state.move_index > 0:
        st.session_state.move_index -= 1
        st.session_state.final_move_completed = False
        if "success_message" in st.session_state:
            del st.session_state.success_message
        update_board()


# Create two columns: one for the board and buttons, one for the move list
col1, col2 = st.columns([3, 1])

with col1:
    if st.session_state.current_opening:
        st.markdown(
            f"""
            <div style='width: 360px; margin-bottom: 10px;'>
                <h3 style='
                    background: linear-gradient(90deg, #0077be, #00a86b);
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                    display: inline-block;
                    font-weight: bold;
                '>
                    {st.session_state.current_opening}
                </h3>
            </div>
            """,
            unsafe_allow_html=True,
        )

        col_prev, col_next, right_col = st.columns([5, 2, 2])

        with col_prev:
            st.button(
                "⬅️ &nbsp; Previous",
                disabled=st.session_state.move_index == 0,
                on_click=update_prev_move,
            )
        with col_next:
            st.button(
                "Next &nbsp;&nbsp;&nbsp;➡️",
                disabled=(st.session_state.move_index >= len(st.session_state.moves))
                or (
                    not hide_next_moves
                    and st.session_state.move_index == len(st.session_state.moves)
                ),
                on_click=update_next_move,
            )

        board_container = st.empty()
        board_container.image(chess.svg.board(board=st.session_state.board, size=400))

        # User input for next move
        if hide_next_moves and st.session_state.move_index < len(
            st.session_state.moves
        ):
            col_input, col_submit, col_right = st.columns([3, 1, 1])

            def submit_move():
                if st.session_state.user_move.strip() == "":
                    return
                user_move = st.session_state.user_move
                try:
                    user_chess_move = st.session_state.board.parse_san(user_move)
                    correct_move = st.session_state.moves[st.session_state.move_index]
                    if user_chess_move == correct_move:
                        update_score()
                        st.session_state.move_index += 1
                        if st.session_state.move_index == len(st.session_state.moves):
                            st.session_state.success_message = "🎉 &nbsp; Well done!"
                            st.session_state.final_move_completed = True
                            st.session_state.completed_openings.add(
                                st.session_state.current_opening
                            )
                        else:
                            st.session_state.success_message = (
                                "✅ Correct! Moving to the next one"
                            )

                        st.session_state.user_move = ""
                        update_board()
                    else:
                        st.session_state.error_message = "😭 Incorrect move. Try again!"
                except ValueError as e:
                    error_message = str(e).lower()
                    if (
                        "invalid san" in error_message
                        or "unexpected" in error_message
                        or "unterminated" in error_message
                    ):
                        st.session_state.error_message = "🚫 Invalid format. Please use standard SAN notation (e.g., e4 or Nf3)."
                    else:
                        st.session_state.error_message = "⛔ Invalid move. This move is not allowed in the current position."

            with col_input:
                user_move = st.text_input(
                    label="Enter your move",
                    placeholder="Enter your move (e.g., e4 or Nf3)",
                    key="user_move",
                    value=st.session_state.user_move,
                    label_visibility="hidden",
                    on_change=submit_move,
                )
                if "error_message" in st.session_state:
                    st.error(st.session_state.error_message)
                    del st.session_state.error_message
                elif "success_message" in st.session_state:
                    st.success(st.session_state.success_message)
                    if not st.session_state.final_move_completed:
                        del st.session_state.success_message

            with col_submit:
                st.markdown("<br>", unsafe_allow_html=True)
                submit_button = st.button(
                    "Submit",
                    on_click=submit_move,
                )

        if st.session_state.final_move_completed:
            col_success, col_empty = st.columns([1, 2])
            with col_success:
                st.success("🎉 &nbsp; Well done!")

    else:
        st.info("Please select an opening from the sidebar to begin.")

with col2:
    if st.session_state.current_opening:
        st.subheader("Moves", divider="green")
        move_text = ""
        current_node = chess.pgn.Game()
        for i, move in enumerate(st.session_state.moves):
            if i % 2 == 0:
                move_number = i // 2 + 1
                move_text += f"{move_number}. "
            san_move = current_node.board().san(move)
            if i < st.session_state.move_index:
                move_text += f"**{san_move}** "
            elif hide_next_moves:
                move_text += "... "
            else:
                move_text += f"{san_move} "
            if i % 2 == 1 or i == len(st.session_state.moves) - 1:
                move_text += "\n"
            current_node = current_node.add_variation(move)
        st.markdown(move_text)

with st.sidebar:
    st.markdown("---")

    # score = update_score()
    st.metric(
        label="Score",
        value=st.session_state.score,
        help="1 point per correct move",
    )

    col1, col2 = st.columns([2, 1])
    with col1:
        st.subheader("Completed Openings")
    with col2:
        if st.button("Reset", key="reset_completed", help="Reset completed openings"):
            st.session_state.completed_openings.clear()
            st.rerun()

    with st.expander("View Completed Openings"):
        if st.session_state.completed_openings:
            for completed_opening in st.session_state.completed_openings:
                st.markdown(f"- {completed_opening}")
        else:
            st.markdown("No openings completed yet.")