Paste a line, play on from here, learn the opening
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

Paste a line from the clipboard (Ctrl+V on a game, the move menu, ☰):
chess-core paste.rs plans where the text fits without touching the game — a
PGN game where its moves part from this one along any branch, or where one of
its positions occurs (another move order, noted); a fragment (SAN, numbered
or not, «…» for black, UCI) after the selected move, instead of it, or at its
move number — and grafts the new moves with their comments, symbols and
variations (the pasted game's alternatives along the way too) as one undo
step, the players' names after the line. A game with no position in common
is refused with a message; a line going elsewhere than the selected move is
asked about; an impossible move inserts nothing.

Play on from here (the move menu, Ctrl+G on a game, ☰): the play dialog shows
the position on a small board and the game it comes from; the new game holds
the moves up to it (Maia sees the history, repetitions count), dimmed during
play, with a comment saying where it comes from; take-backs, abort and resign
count only the new moves; the source game waits under it («⬅ Back to the
game»); the side to move plays by default, a rematch keeps the colour.

Learn the opening up to this move (the move menu, ☰): a training screen over
the game; the user plays both sides; a wrong move is counted, shown for
400 ms in red with a short sound and taken back; from the third mistake on a
move «Show the move» puts an arrow (the run marked with a hint); at the end
the mistakes by move, the line's runs (last, best, clean in a row, recent),
«Again» (Enter). Runs are kept in training.json by the line (start position
and moves), shared between games; an entry or a file that does not read is
kept aside, not lost. New sounds Wrong (Kenney, CC0) and Success (Lichess
Victory, Kenney).

Keys of the game do nothing under a modal question or dialog. Dev hooks
CP_PASTE_LINE, CP_PLAY_FROM, CP_TRAIN, CP_TRAIN_MOVES, CP_TRAIN_KEEP,
CP_TRAINING_FILE. Texts in nine languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-25 14:51:09 +03:00
parent 1b631ec536
commit a5614d91fc
25 changed files with 3632 additions and 58 deletions

View file

@ -169,7 +169,8 @@ pub fn overlay_open_besides(ctx: &egui::Context, own: &[egui::Id]) -> bool {
/// What starts once the played game is closed.
enum PlayNext {
Rematch(crate::play::Start),
Dialog,
/// The play dialog again (from the same position, for a game from a position).
Dialog(Option<Box<crate::play::StartFrom>>),
}
#[derive(Clone, Copy, PartialEq)]
@ -239,6 +240,8 @@ pub struct App {
#[derive(Default)]
struct DebugStartup {
open: Option<usize>,
/// `CP_PLAY_FROM=white|black`: the game against Maia from the move reached.
play_from: Option<crate::play::Start>,
ply: usize,
analyze: bool,
/// `CP_SCREENSHOT=<file.png>`: go fullscreen, wait `CP_SCREENSHOT_DELAY` seconds,
@ -264,6 +267,7 @@ impl DebugStartup {
let num = |k| std::env::var(k).ok().and_then(|v| v.parse::<usize>().ok());
Self {
open: num("CP_OPEN"),
play_from: None,
ply: num("CP_PLY").unwrap_or(0),
analyze: std::env::var("CP_ANALYZE").is_ok(),
screenshot: std::env::var_os("CP_SCREENSHOT").map(PathBuf::from),
@ -482,6 +486,7 @@ impl App {
user_elo: self.settings.rating,
user_name: self.settings.your_name.clone(),
clock,
from: None,
},
);
}
@ -572,6 +577,39 @@ impl App {
if std::env::var_os("CP_COMMENT_EDIT").is_some() {
g.debug_comment_edit();
}
if let Ok(text) = std::env::var("CP_PASTE_LINE") {
g.debug_paste(&text);
}
// `CP_PLAY_FROM=dialog`: the play dialog from the move reached;
// `white|black[,strength]`: the game at once.
if let Ok(spec) = std::env::var("CP_PLAY_FROM")
&& let Some(from) = g.debug_play_from()
{
let mut parts = spec.split(',');
let side = parts.next().unwrap_or("dialog");
let strength = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1500);
let user = match side {
"white" => Some(chess_core::shakmaty::Color::White),
"black" => Some(chess_core::shakmaty::Color::Black),
_ => None,
};
match user {
Some(user) => {
self.debug.play_from = Some(crate::play::Start {
user,
strength,
user_elo: self.settings.rating,
user_name: self.settings.your_name.clone(),
clock: self.settings.play.clock,
from: Some(Box::new(from)),
})
}
None => {
self.play_dialog =
Some(crate::play::Dialog::new_from(&self.settings, from));
}
}
}
if std::env::var("CP_ENGINE_PANEL").is_ok() {
g.debug_open_engine_settings();
}
@ -586,6 +624,19 @@ impl App {
g.debug_review(&self.settings, ctx, v != "dialog");
}
}
if let Some(start) = self.debug.play_from.take() {
self.start_play(ctx, start);
}
// `CP_TRAIN=1`: learning the opening up to the move reached; `CP_TRAIN_MOVES`:
// moves made in it (UCI).
if std::env::var_os("CP_TRAIN").is_some()
&& let Some(start) = self.game.as_ref().and_then(|g| g.debug_train())
{
self.open_training(start);
if let (Ok(moves), Some(g)) = (std::env::var("CP_TRAIN_MOVES"), self.game.as_mut()) {
g.debug_train_moves(&moves);
}
}
if self.debug.analyze {
self.toggle_engine(ctx);
}
@ -1284,6 +1335,70 @@ impl App {
self.game = Some(GameView::new(g, None, Vec::new()));
}
/// What comes after a game against Maia was closed: a rematch, the dialog.
fn play_next_now(&mut self, ctx: &egui::Context) {
match self.play_next.take() {
Some(PlayNext::Rematch(s)) => self.start_play(ctx, s),
Some(PlayNext::Dialog(None)) => {
self.play_dialog = Some(crate::play::Dialog::new(&self.settings))
}
Some(PlayNext::Dialog(Some(from))) => {
self.play_dialog = Some(crate::play::Dialog::new_from(&self.settings, *from))
}
None => {}
}
}
/// A game from a position of another game: its moves to that position, the game
/// it comes from waiting under it (as a game opened from the reference does).
fn game_from(&mut self, from: &crate::play::StartFrom) {
let mut g = match from
.start_fen
.as_deref()
.and_then(|f| chess_core::StartPosition::from_fen(f).ok())
{
Some(start) => Game::from_start(start),
None => Game::new(),
};
g.set_tag("Date", &chrono::Local::now().format("%Y.%m.%d").to_string());
if !from.moves.is_empty() {
let _ = g.add_line(chess_core::NodeId::ROOT, &from.moves);
}
g.forget_history();
g.mark_saved();
self.open_over(g);
}
/// `g` opens over the current game, which waits under it as it is (as a game
/// opened from the reference does); the engine stops.
fn open_over(&mut self, g: Game) {
self.analysis.stop();
let title = self.game.as_ref().map(|g| g.title());
if let Some(mut prev) = self.game.take() {
prev.suspend();
self.previous_games.push(prev);
}
let mut view = GameView::new(g, None, Vec::new());
view.previous = title;
self.game = Some(view);
}
/// Learning the opening of the current game: the training opens over it.
fn open_training(&mut self, start: crate::train::TrainStart) {
let g = match start
.start_fen
.as_deref()
.and_then(|f| chess_core::StartPosition::from_fen(f).ok())
{
Some(s) => Game::from_start(s),
None => Game::new(),
};
self.open_over(g);
if let Some(view) = self.game.as_mut() {
view.start_training(start);
}
}
/// A new game against Maia (the weights are there: the dialog saw to it).
fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) {
let Some(weights) = crate::maia_download::installed() else {
@ -1299,7 +1414,10 @@ impl App {
.and_then(|e| e.executable())
.filter(|p| p.is_file())
});
self.new_game();
match &start.from {
Some(from) => self.game_from(from),
None => self.new_game(),
}
if let Some(g) = self.game.as_mut() {
g.start_play(start, weights, judge, ctx);
}
@ -1781,6 +1899,8 @@ impl App {
let closed = self.game.take();
if intent == CloseIntent::ReturnToPrevious {
self.game = self.previous_games.pop();
// A rematch from a position goes on over the same game.
self.play_next_now(ctx);
return;
}
// Games left for others (reference tab) with unsaved edits are asked about one
@ -1804,13 +1924,7 @@ impl App {
{
self.library.reveal(&src.path, src.index);
}
match self.play_next.take() {
Some(PlayNext::Rematch(s)) => self.start_play(ctx, s),
Some(PlayNext::Dialog) => {
self.play_dialog = Some(crate::play::Dialog::new(&self.settings))
}
None => {}
}
self.play_next_now(ctx);
if let Some((path, start, line, flipped)) = self.find_after_close.take() {
self.library.show_position(&path, start, line, flipped, ctx);
}
@ -2154,7 +2268,9 @@ impl eframe::App for App {
self.own.then_close = None;
self.new_base_dialog(own_db::AfterCreate::Shelf);
}
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) && self.game.is_none() {
// In the library a game from the start; on a game's screen the game plays on
// from its position (the game view takes Ctrl+G there).
if self.game.is_none() && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) {
self.play_dialog = Some(crate::play::Dialog::new(&self.settings));
}
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() {
@ -2246,7 +2362,9 @@ impl eframe::App for App {
.and_then(|g| g.play_end.clone())
.map(|e| {
let mut s = e.start;
// From a position the colour is part of the task: the same.
s.user = match self.settings.play.color {
_ if s.from.is_some() => s.user,
crate::play::ColorChoice::Random => {
if crate::play::random_unit() < 0.5 {
chess_core::shakmaty::Color::White
@ -2259,13 +2377,34 @@ impl eframe::App for App {
s
});
if let Some(s) = next {
// From a position: back over the game it came from.
let intent = if s.from.is_some() && !self.previous_games.is_empty() {
CloseIntent::ReturnToPrevious
} else {
CloseIntent::BackToLibrary
};
self.play_next = Some(PlayNext::Rematch(s));
self.request_close(&ctx, CloseIntent::BackToLibrary);
self.request_close(&ctx, intent);
}
}
GameAction::PlayAgain => {
self.play_next = Some(PlayNext::Dialog);
self.request_close(&ctx, CloseIntent::BackToLibrary);
let from = self
.game
.as_ref()
.and_then(|g| g.play_end.as_ref())
.and_then(|e| e.start.from.clone());
let intent = if from.is_some() && !self.previous_games.is_empty() {
CloseIntent::ReturnToPrevious
} else {
CloseIntent::BackToLibrary
};
self.play_next = Some(PlayNext::Dialog(from));
self.request_close(&ctx, intent);
}
GameAction::Train(start) => self.open_training(*start),
GameAction::PlayFrom(from) => {
self.play_dialog =
Some(crate::play::Dialog::new_from(&self.settings, *from));
}
GameAction::AddToDatabase => {
if let Some(g) = self.game.as_mut() {
@ -2538,8 +2677,12 @@ impl eframe::App for App {
.order(egui::Order::Foreground)
.show(&ctx, |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(msg.as_str()).size(14.0));
// Long messages wrap: at most 560 wide, inside a narrow window.
ui.set_max_width((ctx.content_rect().width() - 32.0).min(560.0));
ui.horizontal_wrapped(|ui| {
ui.add(
egui::Label::new(RichText::new(msg.as_str()).size(14.0)).wrap(),
);
if undo && ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() {
undo_clicked = true;
}

View file

@ -558,6 +558,10 @@ pub enum Sound {
Checkmate,
/// A game lost — here: Maia offers to resign.
Defeat,
/// Not the move of the line (learning an opening).
Wrong,
/// The line done (learning an opening).
Success,
}
pub fn sound_bytes(set: SoundSet, sound: Sound) -> &'static [u8] {
@ -599,6 +603,15 @@ pub fn sound_bytes(set: SoundSet, sound: Sound) -> &'static [u8] {
(SoundSet::Wood, Sound::Defeat) => s!("wood", "Defeat"),
(SoundSet::Glass, Sound::Defeat) => s!("glass", "Defeat"),
(SoundSet::Clicks, Sound::Defeat) => s!("clicks", "Defeat"),
// One short falling tone for every set (Kenney, CC0).
(_, Sound::Wrong) => s!("common", "Wrong"),
(SoundSet::Sfx, Sound::Success) => s!("sfx", "Success"),
(SoundSet::Piano, Sound::Success) => s!("piano", "Success"),
(SoundSet::Futuristic, Sound::Success) => s!("futuristic", "Success"),
(SoundSet::Nes, Sound::Success) => s!("nes", "Success"),
(SoundSet::Wood, Sound::Success) => s!("wood", "Success"),
(SoundSet::Glass, Sound::Success) => s!("glass", "Success"),
(SoundSet::Clicks, Sound::Success) => s!("clicks", "Success"),
}
}

View file

@ -176,6 +176,8 @@ pub struct BoardView<'a> {
pub premove: Option<Color>,
/// A pawn reaching the last rank becomes a queen without asking.
pub auto_queen: bool,
/// The squares of a wrong move, in red (learning an opening).
pub alert: Option<(Square, Square)>,
}
impl BoardView<'_> {
@ -327,6 +329,11 @@ impl BoardView<'_> {
if let Some(sel) = state.selected {
hl(&painter, sel, self.theme.selected);
}
if let Some((from, to)) = self.alert {
let red = ui.visuals().error_fg_color.gamma_multiply(0.45);
hl(&painter, from, red);
hl(&painter, to, red);
}
if self.pos.is_check()
&& let Some(k) = self.pos.board().king_of(self.pos.turn())
{

View file

@ -525,6 +525,7 @@ impl SearchBoard {
animation: settings.animation.seconds(),
premove: None,
auto_queen: settings.auto_queen,
alert: None,
};
let played = ui
.allocate_ui(vec2(side, side), |ui| view.show(ui, &mut self.board))

File diff suppressed because it is too large Load diff

View file

@ -11001,6 +11001,779 @@ const ROWS: &[[&str; 9]] = &[
"taslim bo‘lmoqda",
"беріледі",
],
// --- paste a line ---
[
"Paste a line from the clipboard (Ctrl+V)",
"Вставить вариант из буфера (Ctrl+V)",
"Coller une variante depuis le presse-papiers (Ctrl+V)",
"Variante aus der Zwischenablage einfügen (Ctrl+V)",
"Pegar una variante del portapapeles (Ctrl+V)",
"Incolla una variante dagli appunti (Ctrl+V)",
"Colar uma variante da área de transferência (Ctrl+V)",
"Buferdan variant qo‘yish (Ctrl+V)",
"Буферден вариант қою (Ctrl+V)",
],
[
"The clipboard holds no moves",
"В буфере нет ходов",
"Le presse-papiers ne contient aucun coup",
"Die Zwischenablage enthält keine Züge",
"El portapapeles no contiene jugadas",
"Gli appunti non contengono mosse",
"A área de transferência não contém lances",
"Buferda yurishlar yo‘q",
"Буферде жүрістер жоқ",
],
[
"These moves fit neither after {move} nor instead of it",
"Эти ходы нельзя сделать ни после {move}, ни вместо него",
"Ces coups ne peuvent être joués ni après {move}, ni à sa place",
"Diese Züge passen weder nach {move} noch an seiner Stelle",
"Estas jugadas no caben ni después de {move} ni en su lugar",
"Queste mosse non si possono giocare né dopo {move} né al suo posto",
"Estes lances não cabem nem depois de {move} nem no lugar dele",
"Bu yurishlarni {move} yurishidan keyin ham, uning o‘rniga ham qilib bo‘lmaydi",
"Бұл жүрістерді {move} жүрісінен кейін де, оның орнына да жасау мүмкін емес",
],
[
"The move {move} is impossible — nothing inserted",
"Ход {move} невозможен — ничего не вставлено",
"Le coup {move} est impossible — rien n’a été inséré",
"Der Zug {move} ist unmöglich — nichts eingefügt",
"La jugada {move} es imposible — no se insertó nada",
"La mossa {move} è impossibile — non è stato inserito nulla",
"O lance {move} é impossível — nada foi inserido",
"{move} yurishi mumkin emas — hech narsa qo‘yilmadi",
"{move} жүрісі мүмкін емес — ештеңе қойылмады",
],
[
"The game in the clipboard does not fit: none of its positions occur in this game",
"Партия из буфера сюда не подходит: в этой партии нет её позиций",
"La partie du presse-papiers ne convient pas : aucune de ses positions n’apparaît dans cette partie",
"Die Partie aus der Zwischenablage passt nicht: keine ihrer Stellungen kommt in dieser Partie vor",
"La partida del portapapeles no encaja: ninguna de sus posiciones aparece en esta partida",
"La partita negli appunti non è compatibile: nessuna delle sue posizioni compare in questa partita",
"A partida da área de transferência não se encaixa: nenhuma de suas posições ocorre nesta partida",
"Buferdagi partiya bu yerga mos kelmaydi: uning pozitsiyalari bu partiyada yo‘q",
"Буфердегі партия бұл жерге сәйкес келмейді: оның позициялары бұл партияда жоқ",
],
[
"These moves are already in the game",
"Эти ходы уже есть в партии",
"Ces coups figurent déjà dans la partie",
"Diese Züge sind bereits in der Partie",
"Estas jugadas ya están en la partida",
"Queste mosse sono già nella partita",
"Estes lances já estão na partida",
"Bu yurishlar partiyada allaqachon bor",
"Бұл жүрістер партияда бұрыннан бар",
],
[
"These moves are already in the game — the comments from the clipboard were not carried over",
"Эти ходы уже есть в партии — комментарии из буфера не перенесены",
"Ces coups figurent déjà dans la partie — les commentaires du presse-papiers n’ont pas été repris",
"Diese Züge sind bereits in der Partie — die Kommentare aus der Zwischenablage wurden nicht übernommen",
"Estas jugadas ya están en la partida — los comentarios del portapapeles no se trasladaron",
"Queste mosse sono già nella partita — i commenti degli appunti non sono stati riportati",
"Estes lances já estão na partida — os comentários da área de transferência não foram transferidos",
"Bu yurishlar partiyada allaqachon bor — buferdagi izohlar ko‘chirilmadi",
"Бұл жүрістер партияда бұрыннан бар — буфердегі түсініктемелер көшірілмеді",
],
[
"By another move order: {moves}",
"Другим порядком ходов: {moves}",
"Par un autre ordre de coups : {moves}",
"Mit anderer Zugfolge: {moves}",
"Con otro orden de jugadas: {moves}",
"Con un altro ordine di mosse: {moves}",
"Por outra ordem de lances: {moves}",
"Boshqa yurishlar tartibida: {moves}",
"Басқа жүріс ретімен: {moves}",
],
[
"The game is continued: {moves} (Ctrl+Z to undo)",
"Партия продолжена: {moves} (Ctrl+Z — отменить)",
"Partie prolongée : {moves} (Ctrl+Z pour annuler)",
"Partie fortgesetzt: {moves} (Ctrl+Z zum Rückgängigmachen)",
"Partida continuada: {moves} (Ctrl+Z para deshacer)",
"Partita proseguita: {moves} (Ctrl+Z per annullare)",
"Partida continuada: {moves} (Ctrl+Z para desfazer)",
"Partiya davom ettirildi: {moves} (bekor qilish: Ctrl+Z)",
"Партия жалғастырылды: {moves} (болдырмау — Ctrl+Z)",
],
[
"Line {moves} inserted after {move} (Ctrl+Z to undo)",
"Вариант {moves} вставлен после {move} (Ctrl+Z — отменить)",
"Variante {moves} insérée après {move} (Ctrl+Z pour annuler)",
"Variante {moves} nach {move} eingefügt (Ctrl+Z zum Rückgängigmachen)",
"Variante {moves} insertada después de {move} (Ctrl+Z para deshacer)",
"Variante {moves} inserita dopo {move} (Ctrl+Z per annullare)",
"Variante {moves} inserida depois de {move} (Ctrl+Z para desfazer)",
"{moves} varianti {move} yurishidan keyin qo‘yildi (bekor qilish: Ctrl+Z)",
"{moves} варианты {move} жүрісінен кейін қойылды (болдырмау — Ctrl+Z)",
],
[
"Line {moves} inserted at the start of the game (Ctrl+Z to undo)",
"Вариант {moves} вставлен в начале партии (Ctrl+Z — отменить)",
"Variante {moves} insérée au début de la partie (Ctrl+Z pour annuler)",
"Variante {moves} am Anfang der Partie eingefügt (Ctrl+Z zum Rückgängigmachen)",
"Variante {moves} insertada al inicio de la partida (Ctrl+Z para deshacer)",
"Variante {moves} inserita all’inizio della partita (Ctrl+Z per annullare)",
"Variante {moves} inserida no início da partida (Ctrl+Z para desfazer)",
"{moves} varianti partiya boshiga qo‘yildi (bekor qilish: Ctrl+Z)",
"{moves} варианты партияның басына қойылды (болдырмау — Ctrl+Z)",
],
[
"The clipboard has {count} games — the first one is inserted.",
"В буфере партий: {count} — вставлена первая.",
"Parties dans le presse-papiers : {count} — la première est insérée.",
"Partien in der Zwischenablage: {count} — die erste wurde eingefügt.",
"Partidas en el portapapeles: {count} — se insertó la primera.",
"Partite negli appunti: {count} — è stata inserita la prima.",
"Partidas na área de transferência: {count} — a primeira foi inserida.",
"Buferdagi partiyalar: {count} — birinchisi qo‘yildi.",
"Буфердегі партиялар: {count} — біріншісі қойылды.",
],
[
"the start of the game",
"начало партии",
"le début de la partie",
"der Partieanfang",
"el inicio de la partida",
"l’inizio della partita",
"o início da partida",
"partiya boshi",
"партия басы",
],
[
"The game in the clipboard parts from this one at the start of the game.",
"Партия из буфера расходится с этой в самом начале.",
"La partie du presse-papiers diverge de celle-ci dès le début.",
"Die Partie aus der Zwischenablage weicht von dieser gleich am Anfang ab.",
"La partida del portapapeles se separa de esta desde el inicio.",
"La partita negli appunti si discosta da questa fin dall’inizio.",
"A partida da área de transferência diverge desta logo no início.",
"Buferdagi partiya bu partiyadan boshidanoq ajraladi.",
"Буфердегі партия бұл партиядан ең басында ажырайды.",
],
[
"The game in the clipboard parts from this one before the selected move: after {from}, not after {cursor}.",
"Партия из буфера расходится с этой раньше выбранного хода: после {from}, а не после {cursor}.",
"La partie du presse-papiers diverge de celle-ci avant le coup sélectionné : après {from}, et non après {cursor}.",
"Die Partie aus der Zwischenablage weicht von dieser schon vor dem gewählten Zug ab: nach {from}, nicht nach {cursor}.",
"La partida del portapapeles se separa de esta antes de la jugada seleccionada: después de {from}, no después de {cursor}.",
"La partita negli appunti si discosta da questa prima della mossa selezionata: dopo {from}, non dopo {cursor}.",
"A partida da área de transferência diverge desta antes do lance selecionado: depois de {from}, não depois de {cursor}.",
"Buferdagi partiya bu partiyadan tanlangan yurishdan oldin ajraladi: {from} yurishidan keyin, {cursor} yurishidan keyin emas.",
"Буфердегі партия бұл партиядан таңдалған жүрістен бұрын ажырайды: {from} жүрісінен кейін, {cursor} жүрісінен кейін емес.",
],
[
"The game in the clipboard parts from this one in another line: after {from}.",
"Партия из буфера расходится с этой в другом варианте: после {from}.",
"La partie du presse-papiers diverge de celle-ci dans une autre variante : après {from}.",
"Die Partie aus der Zwischenablage weicht von dieser in einer anderen Variante ab: nach {from}.",
"La partida del portapapeles se separa de esta en otra variante: después de {from}.",
"La partita negli appunti si discosta da questa in un’altra variante: dopo {from}.",
"A partida da área de transferência diverge desta em outra variante: depois de {from}.",
"Buferdagi partiya bu partiyadan boshqa variantda ajraladi: {from} yurishidan keyin.",
"Буфердегі партия бұл партиядан басқа вариантта ажырайды: {from} жүрісінен кейін.",
],
[
"Insert after {move}",
"Вставить после {move}",
"Insérer après {move}",
"Nach {move} einfügen",
"Insertar después de {move}",
"Inserisci dopo {move}",
"Inserir depois de {move}",
"{move} yurishidan keyin qo‘yish",
"{move} жүрісінен кейін қою",
],
[
"Insert at the start",
"Вставить в начале",
"Insérer au début",
"Am Anfang einfügen",
"Insertar al inicio",
"Inserisci all’inizio",
"Inserir no início",
"Boshiga qo‘yish",
"Басына қою",
],
[
"Insert the line earlier?",
"Вставить вариант раньше?",
"Insérer la variante plus tôt ?",
"Variante früher einfügen?",
"¿Insertar la variante antes?",
"Inserire la variante prima?",
"Inserir a variante antes?",
"Variant oldinroq qo‘yilsinmi?",
"Вариант ертерек қойылсын ба?",
],
[
"Paste a line from the clipboard",
"Вставить вариант из буфера",
"Coller une variante depuis le presse-papiers",
"Variante aus der Zwischenablage einfügen",
"Pegar una variante del portapapeles",
"Incolla una variante dagli appunti",
"Colar uma variante da área de transferência",
"Buferdan variant qo‘yish",
"Буферден вариант қою",
],
[
"Moves or a PGN game from the clipboard, as a variation from where they part from this game",
"Ходы или партия PGN из буфера — вариантом с того места, где они расходятся с этой партией",
"Des coups ou une partie PGN du presse-papiers, en variante à partir de l’endroit où ils divergent de cette partie",
"Züge oder eine PGN-Partie aus der Zwischenablage, als Variante ab der Stelle, an der sie von dieser Partie abweichen",
"Jugadas o una partida PGN del portapapeles, como variante desde donde se separan de esta partida",
"Mosse o una partita PGN dagli appunti, come variante dal punto in cui si discostano da questa partita",
"Lances ou uma partida PGN da área de transferência, como variante a partir de onde divergem desta partida",
"Buferdagi yurishlar yoki PGN partiya — bu partiyadan ajralgan joyidan variant sifatida",
"Буфердегі жүрістер немесе PGN партиясы — осы партиядан ажырайтын жерден вариант ретінде",
],
// --- play on from here ---
[
"Play on from here… (Ctrl+G)",
"Играть отсюда… (Ctrl+G)",
"Jouer à partir d’ici… (Ctrl+G)",
"Von hier aus spielen… (Ctrl+G)",
"Jugar desde aquí… (Ctrl+G)",
"Gioca da qui… (Ctrl+G)",
"Jogar a partir daqui… (Ctrl+G)",
"Shu yerdan o‘ynash… (Ctrl+G)",
"Осы жерден ойнау… (Ctrl+G)",
],
[
"Play on from here…",
"Играть отсюда…",
"Jouer à partir d’ici…",
"Von hier aus spielen…",
"Jugar desde aquí…",
"Gioca da qui…",
"Jogar a partir daqui…",
"Shu yerdan o‘ynash…",
"Осы жерден ойнау…",
],
[
"A game against Maia from this position",
"Партия с Maia из этой позиции",
"Une partie contre Maia à partir de cette position",
"Eine Partie gegen Maia aus dieser Stellung",
"Una partida contra Maia desde esta posición",
"Una partita contro Maia da questa posizione",
"Uma partida contra Maia a partir desta posição",
"Shu pozitsiyadan Maia bilan o‘yin",
"Осы позициядан Maia-мен партия",
],
[
"The game is over here: {why}",
"Здесь партия окончена: {why}",
"La partie est terminée ici : {why}",
"Hier ist die Partie zu Ende: {why}",
"Aquí la partida ha terminado: {why}",
"Qui la partita è finita: {why}",
"Aqui a partida terminou: {why}",
"Bu yerda o‘yin tugagan: {why}",
"Мұнда партия аяқталған: {why}",
],
[
"From the position after {move}",
"С позиции после {move}",
"À partir de la position après {move}",
"Aus der Stellung nach {move}",
"Desde la posición tras {move}",
"Dalla posizione dopo {move}",
"A partir da posição após {move}",
"{move} yurishidan keyingi pozitsiyadan",
"{move} жүрісінен кейінгі позициядан",
],
[
"From the game's starting position",
"С начальной позиции партии",
"À partir de la position de départ de la partie",
"Aus der Anfangsstellung der Partie",
"Desde la posición inicial de la partida",
"Dalla posizione iniziale della partita",
"A partir da posição inicial da partida",
"O‘yinning boshlang‘ich pozitsiyasidan",
"Партияның бастапқы позициясынан",
],
[
"from the game {game}",
"из партии {game}",
"de la partie {game}",
"aus der Partie {game}",
"de la partida {game}",
"dalla partita {game}",
"da partida {game}",
"{game} o‘yinidan",
"{game} партиясынан",
],
[
"The moves before the null move (--) are not carried over",
"Ходы до пропуска хода (--) в игру не войдут",
"Les coups avant le coup nul (--) ne sont pas repris",
"Die Züge vor dem Nullzug (--) werden nicht übernommen",
"Las jugadas antes de la jugada nula (--) no se incluyen",
"Le mosse prima della mossa nulla (--) non vengono riprese",
"Os lances antes do lance nulo (--) não são incluídos",
"Bo‘sh yurishdan (--) oldingi yurishlar o‘yinga kirmaydi",
"Бос жүріске (--) дейінгі жүрістер ойынға кірмейді",
],
[
"Continued from {game}, after {move}. From here on, a game against Maia {elo}.",
"Продолжение партии {game}, после {move}. Дальше — игра с Maia {elo}.",
"Suite de la partie {game}, après {move}. À partir d’ici, une partie contre Maia {elo}.",
"Fortsetzung der Partie {game} nach {move}. Ab hier eine Partie gegen Maia {elo}.",
"Continuación de la partida {game}, tras {move}. A partir de aquí, una partida contra Maia {elo}.",
"Seguito della partita {game}, dopo {move}. Da qui, una partita contro Maia {elo}.",
"Continuação da partida {game}, após {move}. A partir daqui, uma partida contra Maia {elo}.",
"{game} o‘yinining davomi, {move} dan keyin. Bundan keyin — Maia {elo} bilan o‘yin.",
"{game} партиясының жалғасы, {move} кейін. Бұдан әрі — Maia {elo}-мен ойын.",
],
[
"Continued after {move}. From here on, a game against Maia {elo}.",
"Продолжение после {move}. Дальше — игра с Maia {elo}.",
"Suite après {move}. À partir d’ici, une partie contre Maia {elo}.",
"Fortsetzung nach {move}. Ab hier eine Partie gegen Maia {elo}.",
"Continuación tras {move}. A partir de aquí, una partida contra Maia {elo}.",
"Seguito dopo {move}. Da qui, una partita contro Maia {elo}.",
"Continuação após {move}. A partir daqui, uma partida contra Maia {elo}.",
"{move} dan keyingi davomi. Bundan keyin — Maia {elo} bilan o‘yin.",
"{move} кейінгі жалғасы. Бұдан әрі — Maia {elo}-мен ойын.",
],
[
"Continued from {game}. From here on, a game against Maia {elo}.",
"Продолжение партии {game}. Дальше — игра с Maia {elo}.",
"Suite de la partie {game}. À partir d’ici, une partie contre Maia {elo}.",
"Fortsetzung der Partie {game}. Ab hier eine Partie gegen Maia {elo}.",
"Continuación de la partida {game}. A partir de aquí, una partida contra Maia {elo}.",
"Seguito della partita {game}. Da qui, una partita contro Maia {elo}.",
"Continuação da partida {game}. A partir daqui, uma partida contra Maia {elo}.",
"{game} o‘yinining davomi. Bundan keyin — Maia {elo} bilan o‘yin.",
"{game} партиясының жалғасы. Бұдан әрі — Maia {elo}-мен ойын.",
],
[
"From here on, a game against Maia {elo}.",
"Дальше — игра с Maia {elo}.",
"À partir d’ici, une partie contre Maia {elo}.",
"Ab hier eine Partie gegen Maia {elo}.",
"A partir de aquí, una partida contra Maia {elo}.",
"Da qui, una partita contro Maia {elo}.",
"A partir daqui, uma partida contra Maia {elo}.",
"Bundan keyin — Maia {elo} bilan o‘yin.",
"Бұдан әрі — Maia {elo}-мен ойын.",
],
// --- learning an opening ---
[
"Learning the opening: {game}",
"Учим дебют: {game}",
"Apprentissage de l'ouverture : {game}",
"Eröffnung lernen: {game}",
"Aprendiendo la apertura: {game}",
"Studio dell'apertura: {game}",
"Aprendendo a abertura: {game}",
"Debyutni o‘rganish: {game}",
"Дебютті үйрену: {game}",
],
[
"Learning the opening",
"Учим дебют",
"Apprentissage de l'ouverture",
"Eröffnung lernen",
"Aprendiendo la apertura",
"Studio dell'apertura",
"Aprendendo a abertura",
"Debyutni o‘rganish",
"Дебютті үйрену",
],
[
"up to {move}",
"до {move}",
"jusqu'à {move}",
"bis {move}",
"hasta {move}",
"fino a {move}",
"até {move}",
"{move} gacha",
"{move} дейін",
],
[
"Learn the opening up to this move",
"Учить дебют до этого хода",
"Apprendre l'ouverture jusqu'à ce coup",
"Eröffnung bis zu diesem Zug lernen",
"Aprender la apertura hasta esta jugada",
"Studia l'apertura fino a questa mossa",
"Aprender a abertura até este lance",
"Debyutni shu yurishgacha o‘rganish",
"Дебютті осы жүріске дейін үйрену",
],
[
"Select the move to learn up to",
"Выберите ход, до которого учить",
"Choisissez le coup jusqu'auquel apprendre",
"Wählen Sie den Zug, bis zu dem gelernt wird",
"Elige la jugada hasta la que aprender",
"Scegli la mossa fino a cui studiare",
"Escolha o lance até onde aprender",
"O‘rganiladigan oxirgi yurishni tanlang",
"Үйренетін соңғы жүрісті таңдаңыз",
],
[
"The line has a null move (--): it cannot be played on the board",
"В линии есть пропуск хода (--) — его нельзя сыграть на доске",
"La ligne contient un coup nul (--) : il ne peut pas être joué sur l'échiquier",
"Die Linie enthält einen Nullzug (--): er kann nicht auf dem Brett gespielt werden",
"La línea tiene una jugada nula (--): no se puede jugar en el tablero",
"La linea contiene una mossa nulla (--): non si può giocare sulla scacchiera",
"A linha tem um lance nulo (--): ele não pode ser jogado no tabuleiro",
"Liniyada bo‘sh yurish (--) bor: uni taxtada o‘ynab bo‘lmaydi",
"Линияда бос жүріс (--) бар: оны тақтада ойнауға болмайды",
],
[
"Viewing an earlier position · back to training — End",
"Просмотр прошлой позиции · к тренировке — End",
"Position antérieure affichée · retour à l'entraînement — End",
"Frühere Stellung wird angezeigt · zurück zum Training — End",
"Viendo una posición anterior · volver al entrenamiento — End",
"Posizione precedente · torna all'allenamento — End",
"Vendo uma posição anterior · voltar ao treino — End",
"Oldingi pozitsiya ko‘rilmoqda · mashg‘ulotga qaytish — End",
"Бұрынғы позиция көрсетілуде · жаттығуға оралу — End",
],
[
"Move {n} of {last}",
"Ход {n} из {last}",
"Coup {n} sur {last}",
"Zug {n} von {last}",
"Jugada {n} de {last}",
"Mossa {n} di {last}",
"Lance {n} de {last}",
"Yurish {n} / {last}",
"Жүріс {n} / {last}",
],
[
"♔ White to move",
"♔ ход белых",
"♔ Trait aux Blancs",
"♔ Weiß am Zug",
"♔ Juegan blancas",
"♔ Muove il Bianco",
"♔ Brancas jogam",
"♔ Oqlar yuradi",
"♔ Ақтар жүреді",
],
[
"♚ Black to move",
"♚ ход чёрных",
"♚ Trait aux Noirs",
"♚ Schwarz am Zug",
"♚ Juegan negras",
"♚ Muove il Nero",
"♚ Pretas jogam",
"♚ Qoralar yuradi",
"♚ Қаралар жүреді",
],
[
"Mistakes: {n}",
"Ошибок: {n}",
"Erreurs : {n}",
"Fehler: {n}",
"Errores: {n}",
"Errori: {n}",
"Erros: {n}",
"Xatolar: {n}",
"Қателер: {n}",
],
[
"Run {n}",
"Прохождение {n}",
"Passage {n}",
"Durchgang {n}",
"Repaso {n}",
"Giro {n}",
"Rodada {n}",
"Urinish {n}",
"Әрекет {n}",
],
[
"Play the move on the arrow",
"Сделайте ход со стрелки",
"Jouez le coup indiqué par la flèche",
"Spielen Sie den Zug des Pfeils",
"Juega la jugada de la flecha",
"Gioca la mossa indicata dalla freccia",
"Jogue o lance da seta",
"Strelkadagi yurishni qiling",
"Көрсеткідегі жүрісті жасаңыз",
],
[
"× The game has another move here",
"× В партии — другой ход",
"× La partie a un autre coup ici",
"× In der Partie folgt hier ein anderer Zug",
"× En la partida hay otra jugada aquí",
"× Nella partita qui c'è un'altra mossa",
"× Na partida há outro lance aqui",
"× Partiyada bu yerda boshqa yurish",
"× Партияда мұнда басқа жүріс",
],
[
"Show the move",
"Показать ход",
"Montrer le coup",
"Zug zeigen",
"Mostrar la jugada",
"Mostra la mossa",
"Mostrar o lance",
"Yurishni ko‘rsatish",
"Жүрісті көрсету",
],
[
"Not done before",
"Эту линию ещё не проходили",
"Ligne jamais parcourue",
"Diese Linie noch nicht geübt",
"Línea aún no repasada",
"Linea mai ripassata",
"Linha ainda não treinada",
"Bu liniya hali o‘tilmagan",
"Бұл линия әлі өтілмеген",
],
[
"Last time: {n} · clean in a row: {k}",
"Прошлое: {n} · без ошибок подряд: {k}",
"La dernière fois : {n} · sans erreur d'affilée : {k}",
"Zuletzt: {n} · fehlerfrei in Folge: {k}",
"La última vez: {n} · sin errores seguidos: {k}",
"L'ultima volta: {n} · senza errori di fila: {k}",
"Última vez: {n} · sem erros seguidos: {k}",
"Oxirgi marta: {n} · ketma-ket xatosiz: {k}",
"Соңғы рет: {n} · қатарынан қатесіз: {k}",
],
[
"Last time: {n} · best: {m}",
"Прошлое: {n} · лучшее: {m}",
"La dernière fois : {n} · meilleur : {m}",
"Zuletzt: {n} · Bestwert: {m}",
"La última vez: {n} · mejor: {m}",
"L'ultima volta: {n} · migliore: {m}",
"Última vez: {n} · melhor: {m}",
"Oxirgi marta: {n} · eng yaxshi: {m}",
"Соңғы рет: {n} · ең үздігі: {m}",
],
[
"Done with a hint · mistakes: {n}",
"Пройдено с подсказкой · ошибок: {n}",
"Terminé avec un indice · erreurs : {n}",
"Mit Hinweis geschafft · Fehler: {n}",
"Completado con pista · errores: {n}",
"Completato con un aiuto · errori: {n}",
"Concluído com dica · erros: {n}",
"Yordam bilan o‘tildi · xatolar: {n}",
"Көмекпен өтілді · қателер: {n}",
],
[
"Done without mistakes",
"Пройдено без ошибок",
"Terminé sans erreur",
"Fehlerfrei geschafft",
"Completado sin errores",
"Completato senza errori",
"Concluído sem erros",
"Xatosiz o‘tildi",
"Қатесіз өтілді",
],
[
"Done · mistakes: {n}",
"Пройдено · ошибок: {n}",
"Terminé · erreurs : {n}",
"Geschafft · Fehler: {n}",
"Completado · errores: {n}",
"Completato · errori: {n}",
"Concluído · erros: {n}",
"O‘tildi · xatolar: {n}",
"Өтілді · қателер: {n}",
],
[
"Run {n} · best: {m}",
"Прохождение {n} · лучшее: {m}",
"Passage {n} · meilleur : {m}",
"Durchgang {n} · Bestwert: {m}",
"Repaso {n} · mejor: {m}",
"Giro {n} · migliore: {m}",
"Rodada {n} · melhor: {m}",
"Urinish {n} · eng yaxshi: {m}",
"Әрекет {n} · ең үздігі: {m}",
],
[
"clean in a row: {k}",
"без ошибок подряд: {k}",
"sans erreur d'affilée : {k}",
"fehlerfrei in Folge: {k}",
"sin errores seguidos: {k}",
"senza errori di fila: {k}",
"sem erros seguidos: {k}",
"ketma-ket xatosiz: {k}",
"қатарынан қатесіз: {k}",
],
[
"Recent: {runs}",
"Последние: {runs}",
"Récents : {runs}",
"Letzte: {runs}",
"Recientes: {runs}",
"Recenti: {runs}",
"Recentes: {runs}",
"So‘nggilari: {runs}",
"Соңғылары: {runs}",
],
[
"↻ Again",
"↻ Повторить",
"↻ Encore",
"↻ Noch einmal",
"↻ Otra vez",
"↻ Ancora",
"↻ De novo",
"↻ Yana",
"↻ Қайталау",
],
[
"⬅ Back to the game",
"⬅ К партии",
"⬅ Retour à la partie",
"⬅ Zurück zur Partie",
"⬅ Volver a la partida",
"⬅ Torna alla partita",
"⬅ Voltar à partida",
"⬅ Partiyaga qaytish",
"⬅ Партияға оралу",
],
[
"↻ Restart",
"↻ Сначала",
"↻ Recommencer",
"↻ Neu starten",
"↻ Reiniciar",
"↻ Ricomincia",
"↻ Recomeçar",
"↻ Boshidan",
"↻ Басынан",
],
[
"Start the run again; this one is not counted",
"Начать прохождение заново — это не засчитывается",
"Recommencer le passage ; celui-ci n'est pas compté",
"Durchgang neu beginnen; dieser wird nicht gezählt",
"Empezar el repaso de nuevo; este no cuenta",
"Ricomincia il giro; questo non viene contato",
"Começar a rodada de novo; esta não conta",
"Urinishni qaytadan boshlash; bu hisobga olinmaydi",
"Әрекетті қайта бастау; бұл есептелмейді",
],
[
"× Leave",
"× Выйти",
"× Quitter",
"× Beenden",
"× Salir",
"× Esci",
"× Sair",
"× Chiqish",
"× Шығу",
],
[
"Back to the game; the run is not counted (Esc)",
"К партии — прохождение не засчитывается (Esc)",
"Retour à la partie ; le passage n'est pas compté (Esc)",
"Zurück zur Partie; der Durchgang wird nicht gezählt (Esc)",
"Volver a la partida; el repaso no cuenta (Esc)",
"Torna alla partita; il giro non viene contato (Esc)",
"Voltar à partida; a rodada não conta (Esc)",
"Partiyaga qaytish; urinish hisobga olinmaydi (Esc)",
"Партияға оралу; әрекет есептелмейді (Esc)",
],
[
"The engine is off while training",
"Во время тренировки движок выключен",
"Le moteur est désactivé pendant l'entraînement",
"Die Engine ist während des Trainings aus",
"El motor está apagado durante el entrenamiento",
"Il motore è spento durante l'allenamento",
"O motor fica desligado durante o treino",
"Mashg‘ulot paytida dvigatel o‘chiq",
"Жаттығу кезінде қозғалтқыш өшірулі",
],
[
"Mistakes: {n}; the move was shown",
"Ошибок: {n}, ход показан",
"Erreurs : {n} ; le coup a été montré",
"Fehler: {n}; der Zug wurde gezeigt",
"Errores: {n}; se mostró la jugada",
"Errori: {n}; la mossa è stata mostrata",
"Erros: {n}; o lance foi mostrado",
"Xatolar: {n}; yurish ko‘rsatildi",
"Қателер: {n}; жүріс көрсетілді",
],
[
"Mistakes on this move: {n}",
"Ошибок на этом ходу: {n}",
"Erreurs sur ce coup : {n}",
"Fehler bei diesem Zug: {n}",
"Errores en esta jugada: {n}",
"Errori su questa mossa: {n}",
"Erros neste lance: {n}",
"Shu yurishdagi xatolar: {n}",
"Осы жүрістегі қателер: {n}",
],
[
"runs: {n}",
"прохождений: {n}",
"passages : {n}",
"Durchgänge: {n}",
"repasos: {n}",
"giri: {n}",
"rodadas: {n}",
"urinishlar: {n}",
"әрекеттер: {n}",
],
[
"Replay from memory the moves of both sides from the start of the game up to this move",
"Повторите по памяти ходы обеих сторон от начала партии до этого хода",
"Rejouez de mémoire les coups des deux camps depuis le début de la partie jusqu'à ce coup",
"Spielen Sie die Züge beider Seiten vom Partiebeginn bis zu diesem Zug aus dem Gedächtnis nach",
"Repite de memoria las jugadas de ambos bandos desde el inicio de la partida hasta esta jugada",
"Ripeti a memoria le mosse di entrambi i lati dall'inizio della partita fino a questa mossa",
"Repita de memória os lances dos dois lados desde o início da partida até este lance",
"Partiya boshidan shu yurishgacha ikkala tomonning yurishlarini yoddan takrorlang",
"Партия басынан осы жүріске дейін екі жақтың жүрістерін жатқа қайталаңыз",
],
[
"The same position, you play White again",
"Та же позиция, вы снова за белых",
"La même position, vous jouez de nouveau les Blancs",
"Dieselbe Stellung, Sie spielen wieder Weiß",
"La misma posición, vuelves a jugar con blancas",
"La stessa posizione, giochi di nuovo con il Bianco",
"A mesma posição, você joga de novo de brancas",
"O‘sha pozitsiya, yana oqlar bilan o‘ynaysiz",
"Сол позиция, сіз қайтадан ақтармен ойнайсыз",
],
[
"The same position, you play Black again",
"Та же позиция, вы снова за чёрных",
"La même position, vous jouez de nouveau les Noirs",
"Dieselbe Stellung, Sie spielen wieder Schwarz",
"La misma posición, vuelves a jugar con negras",
"La stessa posizione, giochi di nuovo con il Nero",
"A mesma posição, você joga de novo de pretas",
"O‘sha pozitsiya, yana qoralar bilan o‘ynaysiz",
"Сол позиция, сіз қайтадан қаралармен ойнайсыз",
],
];
#[cfg(test)]

View file

@ -2433,6 +2433,7 @@ fn chip(ui: &mut Ui, c: &Condition) -> (bool, bool) {
animation: 0.0,
premove: None,
auto_queen: false,
alert: None,
};
ui.allocate_ui(vec2(160.0, 160.0), |ui| {
view.show(ui, &mut crate::board::BoardState::default())

View file

@ -28,6 +28,7 @@ mod san;
mod settings;
mod settings_ui;
mod sound;
mod train;
mod translate;
mod translate_ui;
mod update;

View file

@ -24,6 +24,11 @@ pub struct Notation<'a> {
pub editor: Option<&'a mut CommentEditor>,
/// A game being played: moves only show their position (no menus, no editing).
pub read_only: bool,
/// Main-line moves up to this ply are dimmed (the moves of the game a game against
/// Maia goes on from).
pub dim_until: Option<u32>,
/// Mistakes on main-line moves (learning an opening): how many, the move was shown.
pub mistakes: Option<&'a HashMap<NodeId, (u32, bool)>>,
}
/// Result of a frame of the notation panel.
@ -49,6 +54,12 @@ pub struct NotationResponse {
pub enum NotationCommand {
Promote,
Delete,
/// Paste a line from the clipboard (docs/design/paste-variation.md).
Paste,
/// A game against Maia from this position (docs/design/play-from-position.md).
PlayFrom,
/// Learn the opening up to this move (docs/design/opening-trainer.md).
Train,
}
/// Which comment of the game: after a move (`After(ROOT)`: the start of the game), or
@ -295,10 +306,43 @@ impl Row {
match id {
Some(id) => {
let resp = ui.interact(cell, ui.id().with(("mv", id.index())), Sense::click());
paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered());
let dim = n
.dim_until
.is_some_and(|p| n.game.node(id).is_some_and(|nd| nd.ply() <= p));
let text_right =
paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered(), dim);
if let Some(mark) = n.marks.and_then(|m| m.get(&id)) {
paint_badge(ui, cell, mark);
}
if let Some(&(count, shown)) = n.mistakes.and_then(|m| m.get(&id)) {
let color = if shown {
ui.visuals().warn_fg_color
} else {
ui.visuals().error_fg_color
};
// A pill right after the move: its own, readable on the selected one.
let galley = ui.painter().layout_no_wrap(
format!("×{count}"),
FontId::proportional(12.0),
Color32::WHITE,
);
let pill = egui::Rect::from_min_size(
egui::pos2(
text_right + 4.0,
cell.center().y - galley.size().y / 2.0 - 1.0,
),
galley.size() + vec2(8.0, 2.0),
);
ui.painter().rect_filled(pill, 7.0, color);
ui.painter()
.galley(pill.min + vec2(4.0, 1.0), galley, Color32::WHITE);
let tip = if shown {
crate::i18n::trf("Mistakes: {n}; the move was shown", &[("n", &count)])
} else {
crate::i18n::trf("Mistakes on this move: {n}", &[("n", &count)])
};
resp.clone().on_hover_text(tip);
}
handle_move_response(ui, &resp, n, id, out);
}
None => {
@ -372,6 +416,16 @@ fn handle_move_response(
}
}
ui.separator();
if ui
.add(egui::Button::new(tr("Paste a line from the clipboard")).shortcut_text("Ctrl+V"))
.on_hover_text(tr(
"Moves or a PGN game from the clipboard, as a variation from where they part from this game",
))
.clicked()
{
out.context = Some((id, NotationCommand::Paste));
ui.close();
}
if is_variation && ui.button(tr("Make main line")).clicked() {
out.context = Some((id, NotationCommand::Promote));
ui.close();
@ -380,6 +434,57 @@ fn handle_move_response(
out.context = Some((id, NotationCommand::Delete));
ui.close();
}
ui.separator();
// A finished position has nothing to play.
let over = n.game.position(id).and_then(|p| {
if p.is_checkmate() {
Some(tr("checkmate"))
} else if p.is_stalemate() {
Some(tr("stalemate"))
} else if p.is_insufficient_material() {
Some(tr("neither side can checkmate"))
} else {
None
}
});
let play = ui
.add_enabled(
over.is_none(),
egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"),
)
.on_hover_text(tr("A game against Maia from this position"));
let play = match over {
Some(why) => play.on_disabled_hover_text(crate::i18n::trf(
"The game is over here: {why}",
&[("why", &why)],
)),
None => play,
};
if play.clicked() {
out.context = Some((id, NotationCommand::PlayFrom));
ui.close();
}
// Learning the opening: the runs of this line so far on the right.
let runs = crate::train::runs_to(n.game, id);
let label = runs
.filter(|&r| r > 0)
.map(|r| crate::i18n::trf("runs: {n}", &[("n", &r)]))
.unwrap_or_default();
let learn = ui
.add_enabled(
runs.is_some(),
egui::Button::new(tr("Learn the opening up to this move")).shortcut_text(label),
)
.on_hover_text(tr(
"Replay from memory the moves of both sides from the start of the game up to this move",
))
.on_disabled_hover_text(tr(
"The line has a null move (--): it cannot be played on the board",
));
if learn.clicked() {
out.context = Some((id, NotationCommand::Train));
ui.close();
}
});
let _ = ui;
}
@ -447,7 +552,8 @@ fn paint_move_cell(
id: NodeId,
current: bool,
hovered: bool,
) {
dim: bool,
) -> f32 {
let visuals = ui.visuals();
if current {
ui.painter()
@ -464,16 +570,20 @@ fn paint_move_cell(
.unwrap_or((String::new(), None));
let text_color = if current {
visuals.selection.stroke.color
} else if dim {
visuals.weak_text_color()
} else {
color.unwrap_or(visuals.text_color())
};
ui.painter().text(
cell.left_center() + vec2(10.0, 0.0),
Align2::LEFT_CENTER,
format!("{san}{sym}"),
FontId::proportional(16.0),
text_color,
);
ui.painter()
.text(
cell.left_center() + vec2(10.0, 0.0),
Align2::LEFT_CENTER,
format!("{san}{sym}"),
FontId::proportional(16.0),
text_color,
)
.right()
}
/// Engine verdict at the right edge of a move cell: a filled pill, unlike the author's NAGs.

View file

@ -672,6 +672,9 @@ pub struct Session {
pub resign_offer: Option<Instant>,
/// «Play to the end»: no more offers in this game.
pub play_on: bool,
/// The last move of the game it goes on from (`ROOT`: a game from the start): the
/// moves up to it are not taken back and do not count as played.
pub floor: chess_core::NodeId,
}
/// What the play dialog starts.
@ -682,6 +685,31 @@ pub struct Start {
pub user_elo: Option<u32>,
pub user_name: String,
pub clock: Option<TimeControl>,
/// A game from a position of another game (docs/design/play-from-position.md).
pub from: Option<Box<StartFrom>>,
}
/// Where a game against Maia starts when it goes on from a game: its start and the
/// moves to the chosen one (the history Maia and the repetitions need).
#[derive(Clone, Debug)]
pub struct StartFrom {
/// The FEN of the game's start (`None`: the standard position) — after the last
/// null move of the path, if there is one.
pub start_fen: Option<String>,
/// The moves from that start to the chosen position.
pub moves: Vec<chess_core::shakmaty::Move>,
/// The position played from.
pub position: Chess,
/// Its last move, for the board (from, to).
pub last: Option<(chess_core::shakmaty::Square, chess_core::shakmaty::Square)>,
/// «14...Ke7» — the move played from (SAN, as data); `None`: the game's start.
pub after: Option<String>,
/// The same as shown («14…Ке7»).
pub after_shown: Option<String>,
/// «Carlsen — Caruana, Wijk aan Zee 2024», when the game says so.
pub game: Option<String>,
/// Null moves before the position were left out.
pub null_dropped: bool,
}
// ----- Maia resigns --------------------------------------------------------------------
@ -818,6 +846,8 @@ pub struct Dialog {
download: Option<crate::maia_download::Download>,
/// «Download and play» was pressed: the game starts once Maia is there.
play_after: bool,
/// The game goes on from a position of another game.
from: Option<StartFrom>,
focus: bool,
}
@ -842,9 +872,21 @@ impl Dialog {
download: None,
play_after: false,
focus: true,
from: None,
}
}
/// The dialog for a game from a position: the side to move plays (not remembered).
pub fn new_from(settings: &crate::settings::Settings, from: StartFrom) -> Dialog {
let mut d = Dialog::new(settings);
d.prefs.color = match from.position.turn() {
Color::White => ColorChoice::White,
Color::Black => ColorChoice::Black,
};
d.from = Some(from);
d
}
fn rating(&self) -> Option<u32> {
self.rating
.trim()
@ -874,8 +916,11 @@ impl Dialog {
.auto_shrink([false, true])
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded)
.show(ui, |ui| {
// In a low window the choices matter more than the introduction.
if body_h >= 420.0 {
// A game from a position: that position, instead of the introduction.
if let Some(from) = &self.from {
position_block(ui, settings, from, self.prefs.color, body_h >= 420.0);
} else if body_h >= 420.0 {
// In a low window the choices matter more than the introduction.
ui.label(
RichText::new(tr(
"Maia plays like a human of the chosen rating: it makes the moves people of that level make, mistakes included.",
@ -1129,13 +1174,19 @@ impl Dialog {
};
settings.your_name = self.name.trim().to_owned();
settings.rating = rating;
// From a position the colour is the side to move's, not a habit.
let color = settings.play.color;
settings.play = self.prefs.clone();
if self.from.is_some() {
settings.play.color = color;
}
out = Some(DialogOutcome::Play(Start {
user,
strength: self.prefs.strength,
user_elo: rating,
user_name: self.name.trim().to_owned(),
clock: self.prefs.clock,
from: self.from.clone().map(Box::new),
}));
}
if ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(0.0, 30.0))).clicked() {
@ -1150,6 +1201,103 @@ impl Dialog {
}
}
/// The position a game goes on from: a small board (turned to the colour chosen) and
/// where it comes from. `board`: room for the board (not in a low window).
fn position_block(
ui: &mut egui::Ui,
settings: &crate::settings::Settings,
from: &StartFrom,
color: ColorChoice,
board: bool,
) {
use egui::RichText;
let bottom = match color {
ColorChoice::White => Color::White,
ColorChoice::Black => Color::Black,
ColorChoice::Random => from.position.turn(),
};
egui::Frame::new()
.inner_margin(egui::Margin::same(8))
.corner_radius(4)
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal_top(|ui| {
if board {
ui.allocate_ui(egui::vec2(112.0, 112.0), |ui| {
let view = crate::board::BoardView {
pos: &from.position,
orientation: bottom,
last_move: from.last,
arrows: &[],
circles: &[],
badge: None,
interactive: false,
show_coords: false,
theme: settings.board_theme.theme(),
pieces: settings.piece_set,
animation: 0.0,
premove: None,
auto_queen: false,
alert: None,
};
let mut state = crate::board::BoardState::default();
view.show(ui, &mut state);
});
ui.add_space(12.0 - ui.spacing().item_spacing.x);
}
ui.vertical(|ui| {
let top = ui.cursor().top();
let title = match &from.after_shown {
Some(m) => {
crate::i18n::trf("From the position after {move}", &[("move", m)])
}
None => tr("From the game's starting position").to_owned(),
};
ui.label(RichText::new(title).strong().size(15.0));
if let Some(g) = &from.game {
// Two lines at most; the whole of it under the pointer.
let text = crate::i18n::trf("from the game {game}", &[("game", g)]);
let mut job = egui::text::LayoutJob::simple(
text.clone(),
egui::FontId::proportional(13.0),
ui.visuals().weak_text_color(),
ui.available_width(),
);
job.wrap.max_rows = 2;
ui.add(egui::Label::new(job)).on_hover_text(text);
}
if from.null_dropped {
ui.label(
RichText::new(tr(
"The moves before the null move (--) are not carried over",
))
.weak()
.size(13.0),
);
}
// The side to move level with the bottom of the board.
let room = if board {
top + 112.0 - ui.cursor().top() - 17.0
} else {
4.0
};
ui.add_space(room.max(4.0));
ui.label(
RichText::new(match from.position.turn() {
Color::White => tr("White to move"),
Color::Black => tr("Black to move"),
})
.size(13.0),
);
});
});
});
}
fn trf_size() -> String {
crate::i18n::trf(
"Maia is downloaded once ({mb} MB, from huggingface.co, the authors' own file).",

387
apps/desktop/src/train.rs Normal file
View file

@ -0,0 +1,387 @@
//! Learning an opening: the user replays from memory the moves of both sides of a
//! line of a game, from its start to the chosen move (docs/design/opening-trainer.md,
//! docs/research/opening-trainer.md).
//!
//! Only the move of the line is right: another move — a move of a variation or one
//! transposing — is a mistake; it is shown for a moment and taken back. From the third
//! mistake on a move the user may ask to see it (the run is then marked «with a hint»).
//! The runs of each line are kept in `training.json`, by the line itself (its start
//! position and moves), so they survive edits of the game and are shared between games
//! with the same line.
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use chess_core::shakmaty::fen::Fen;
use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Move, Square};
use chess_core::{Game, MoveKind, NodeId};
use serde::{Deserialize, Serialize};
/// How long a wrong move stays on the board before it is taken back.
pub const WRONG_SHOWN: Duration = Duration::from_millis(400);
/// From this mistake on one move, the user may ask to see it.
pub const HINT_AFTER: u32 = 3;
/// The runs of a line remembered for its «recent» row.
const RECENT: usize = 10;
/// What a training starts from: the line and how to name it.
#[derive(Clone, Debug)]
pub struct TrainStart {
/// The FEN of the game's start (`None`: the standard position).
pub start_fen: Option<String>,
pub line: Vec<Move>,
/// «Carlsen — Caruana», when the game names its players.
pub game: Option<String>,
/// «Wijk aan Zee 2024», when the game says so.
pub event: Option<String>,
/// The last move of the line as shown («12…Rd8»).
pub up_to: String,
/// Its move number.
pub last_number: u32,
/// The board as the game showed it.
pub flipped: bool,
}
impl TrainStart {
/// The line from the start of `game` to `at` (`None`: no move there, or a null
/// move on the way — it cannot be played on the board).
pub fn from_game(game: &Game, at: NodeId) -> Option<TrainStart> {
let path = game.path(at);
let mut line = Vec::new();
for &n in &path[1..] {
match game.game_move(n)?.kind {
MoveKind::Normal(m) => line.push(m),
MoveKind::Null => return None,
}
}
if line.is_empty() {
return None;
}
let (n, side) = game.move_number(at)?;
let san = &game.game_move(at)?.san;
let up_to = crate::san::show(&match side {
chess_core::shakmaty::Color::White => format!("{n}.{san}"),
chess_core::shakmaty::Color::Black => format!("{n}…{san}"),
})
.into_owned();
let name = |t: &str| {
game.tag(t)
.map(str::trim)
.filter(|v| !v.is_empty() && *v != "?")
};
let players = match (name("White"), name("Black")) {
(None, None) => None,
(w, b) => Some(format!("{} — {}", w.unwrap_or("?"), b.unwrap_or("?"))),
};
let year = name("Date")
.map(|d| d.chars().take(4).collect::<String>())
.filter(|y| y.len() == 4 && y.chars().all(|c| c.is_ascii_digit()));
let event = [name("Event").map(str::to_owned), year]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(" ");
Some(TrainStart {
start_fen: (!game.start().is_standard()).then(|| game.start().fen()),
line,
game: players,
event: (!event.is_empty()).then_some(event),
up_to,
last_number: n,
flipped: false,
})
}
/// The key of the line in the statistics.
pub fn key(&self) -> String {
let start = match self
.start_fen
.as_deref()
.and_then(|f| f.parse::<Fen>().ok())
{
Some(fen) => fen
.into_position::<Chess>(CastlingMode::Standard)
.unwrap_or_default(),
None => Chess::default(),
};
line_key(&start, &self.line)
}
}
/// The key of a line: its start position (no counters) and its moves in UCI.
pub fn line_key(start: &Chess, line: &[Move]) -> String {
let fen = Fen::from_position(start, EnPassantMode::Legal).to_string();
let pos: Vec<&str> = fen.split(' ').take(4).collect();
let moves: Vec<String> = line
.iter()
.map(|m| m.to_uci(CastlingMode::Standard).to_string())
.collect();
format!("{} | {}", pos.join(" "), moves.join(" "))
}
/// A wrong move shown on the board for a moment.
#[derive(Clone, Debug)]
pub struct Flash {
/// The position after it.
pub after: Chess,
pub from: Square,
pub to: Square,
pub until: Instant,
}
/// A training in progress (or done).
pub struct Training {
pub start: TrainStart,
pub key: String,
/// Mistakes on each half-move of the line in this run.
pub mistakes: Vec<u32>,
/// The move was shown (a hint) on each half-move.
pub shown: Vec<bool>,
/// The hint is on the board now (the arrow of the right move).
pub hint: bool,
pub flash: Option<Flash>,
/// The run is over: all the moves made.
pub done: bool,
/// The line's runs before this one.
pub before: LineStats,
/// …and after it, once it is done.
pub after: Option<LineStats>,
}
impl Training {
pub fn new(start: TrainStart) -> Training {
let key = start.key();
let n = start.line.len();
Training {
before: stats(&key),
key,
mistakes: vec![0; n],
shown: vec![false; n],
hint: false,
flash: None,
done: false,
after: None,
start,
}
}
/// The same line again from the start.
pub fn again(&mut self) {
let n = self.start.line.len();
self.before = stats(&self.key);
self.mistakes = vec![0; n];
self.shown = vec![false; n];
self.hint = false;
self.flash = None;
self.done = false;
self.after = None;
}
pub fn total(&self) -> u32 {
self.mistakes.iter().sum()
}
pub fn hinted(&self) -> bool {
self.shown.iter().any(|&s| s)
}
/// The run is over: it counts.
pub fn finish(&mut self) {
self.done = true;
self.hint = false;
self.after = Some(record(&self.key, self.total(), self.hinted()));
}
}
/// What is known of the runs of a line.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct LineStats {
pub runs: u32,
/// Mistakes of the last run.
pub last: Option<u32>,
/// The fewest mistakes of a run without a hint.
pub best: Option<u32>,
/// Runs without mistakes (or hints) in a row, to the last one.
pub clean_streak: u32,
/// The last runs, oldest first: mistakes, a hint.
pub recent: Vec<(u32, bool)>,
/// The day of the last run (for repetition by a schedule later).
pub last_date: String,
}
/// The runs by line, as in the file: an entry that does not read is left as it is.
static STATS: Mutex<Option<serde_json::Map<String, serde_json::Value>>> = Mutex::new(None);
/// The file the tests write instead.
static FILE: Mutex<Option<PathBuf>> = Mutex::new(None);
/// `<local data dir>/training.json` (`CP_TRAINING_FILE` elsewhere: development).
fn file() -> Option<PathBuf> {
if let Some(p) = FILE.lock().ok().and_then(|f| f.clone()) {
return Some(p);
}
if let Some(p) = std::env::var_os("CP_TRAINING_FILE") {
return Some(PathBuf::from(p));
}
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
.map(|d| d.data_local_dir().join("training.json"))
}
fn with_stats<R>(f: impl FnOnce(&mut serde_json::Map<String, serde_json::Value>) -> R) -> R {
let mut guard = STATS.lock().unwrap_or_else(|e| e.into_inner());
let map = guard.get_or_insert_with(load);
f(map)
}
/// The file read; one that does not read as a whole is kept aside
/// (`training.json.unreadable`), not overwritten by the next run.
fn load() -> serde_json::Map<String, serde_json::Value> {
let Some(path) = file() else {
return Default::default();
};
let Ok(bytes) = std::fs::read(&path) else {
return Default::default();
};
match serde_json::from_slice(&bytes) {
Ok(map) => map,
Err(e) => {
let aside = path.with_extension("json.unreadable");
eprintln!(
"training: {} unreadable ({e}), kept as {}",
path.display(),
aside.display()
);
let _ = std::fs::rename(&path, aside);
Default::default()
}
}
}
/// The runs of the line `key` so far (an entry that does not read: none).
pub fn stats(key: &str) -> LineStats {
with_stats(|m| {
m.get(key)
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default()
})
}
/// A run done: counted and written at once.
fn record(key: &str, mistakes: u32, hinted: bool) -> LineStats {
with_stats(|m| {
let mut s: LineStats = m
.get(key)
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
s.runs += 1;
s.last = Some(mistakes);
if !hinted {
s.best = Some(s.best.map_or(mistakes, |b| b.min(mistakes)));
}
s.clean_streak = if mistakes == 0 && !hinted {
s.clean_streak + 1
} else {
0
};
s.recent.push((mistakes, hinted));
if s.recent.len() > RECENT {
s.recent.remove(0);
}
s.last_date = chrono::Local::now().format("%Y-%m-%d").to_string();
if let Ok(v) = serde_json::to_value(&s) {
m.insert(key.to_owned(), v);
}
let out = s;
if let Some(path) = file() {
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(json) = serde_json::to_vec_pretty(m)
&& let Err(e) = crate::settings::write_atomic(&path, &json)
{
eprintln!("training: save failed: {e}");
}
}
out
})
}
/// The runs of the line from the start of `game` to `at`, for the move's menu
/// (`None`: no line there).
pub fn runs_to(game: &Game, at: NodeId) -> Option<u32> {
TrainStart::from_game(game, at).map(|t| stats(&t.key()).runs)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn a_line_is_kept_by_its_moves_and_counted() {
let dir = std::env::temp_dir().join(format!("cp-train-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
*FILE.lock().unwrap() = Some(dir.join("training.json"));
let a = chess_core::parse_str("[White \"A\"]\n\n1. e4 c5 2. Nf3 d6 *").game;
let b = chess_core::parse_str("1. e4 c5 2. Nf3 d6 3. d4 (3. Bb5+) *").game;
let at = |g: &Game, k: usize| g.mainline()[k];
let ta = TrainStart::from_game(&a, at(&a, 3)).unwrap();
let tb = TrainStart::from_game(&b, at(&b, 3)).unwrap();
// The same line in two games: one key.
assert_eq!(ta.key(), tb.key());
assert_eq!(ta.game.as_deref(), Some("A — ?"));
let mut t = Training::new(ta);
t.mistakes[1] = 2;
t.finish();
let s = stats(&t.key);
assert_eq!(
(s.runs, s.last, s.best, s.clean_streak),
(1, Some(2), Some(2), 0)
);
t.again();
t.shown[0] = true;
t.finish();
let s = stats(&t.key);
// A hint: counted, not the best.
assert_eq!((s.runs, s.best), (2, Some(2)));
assert_eq!(s.recent, [(2, false), (0, true)]);
t.again();
t.finish();
let s = stats(&t.key);
assert_eq!((s.best, s.clean_streak), (Some(0), 1));
// Written to the file.
let back: HashMap<String, LineStats> =
serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap();
assert_eq!(back[&t.key].runs, 3);
// An entry that does not read stays in the file as it is.
let mut raw: serde_json::Map<String, serde_json::Value> =
serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap();
raw.insert("x".into(), serde_json::json!({"runs": "bad"}));
std::fs::write(dir.join("training.json"), serde_json::to_vec(&raw).unwrap()).unwrap();
*STATS.lock().unwrap() = None;
t.again();
t.finish();
let raw: serde_json::Map<String, serde_json::Value> =
serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap();
assert_eq!(raw["x"], serde_json::json!({"runs": "bad"}));
assert_eq!(stats(&t.key).runs, 4);
// A file that does not read is kept aside, not lost.
std::fs::write(dir.join("training.json"), b"{ broken").unwrap();
*STATS.lock().unwrap() = None;
t.again();
t.finish();
assert_eq!(
std::fs::read(dir.join("training.json.unreadable")).unwrap(),
b"{ broken"
);
assert_eq!(stats(&t.key).runs, 1);
// A null move on the way: nothing to train.
let n = chess_core::parse_str("1. e4 -- 2. d4 *").game;
assert!(TrainStart::from_game(&n, n.mainline()[2]).is_none());
let _ = std::fs::remove_dir_all(dir);
}
}