Paste a line, play on from here, learn the opening
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:
parent
1b631ec536
commit
a5614d91fc
25 changed files with 3632 additions and 58 deletions
18
CHANGELOG.md
18
CHANGELOG.md
|
|
@ -2,6 +2,24 @@
|
|||
|
||||
All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- Paste a line from the clipboard (Ctrl+V on a game, or the move menu): moves («Nf3 d5»,
|
||||
«12...Rd8», UCI) go after the selected move or instead of it; a PGN game goes where its
|
||||
moves part from this game — along any branch, or by another move order — with its
|
||||
comments, symbols and variations and the players' names at the end. A game that shares
|
||||
no position with this one is not pasted, with a message; a line starting before the
|
||||
selected move is asked about. One Ctrl+Z takes it all back.
|
||||
- Play on from here (the move menu, Ctrl+G on a game): a game against Maia from the
|
||||
position, its moves up to it kept (Maia sees the history, repetitions count); the
|
||||
game you came from waits under it, «⬅ Back to the game» returns to it. The side to
|
||||
move plays by default; a rematch keeps the colour.
|
||||
- Learn the opening (the move menu): replay from memory the moves of both sides up to
|
||||
the chosen move. A wrong move is counted, shown for a moment with a short sound and
|
||||
taken back; from the third mistake on a move you may ask to see it. At the end: the
|
||||
mistakes by move, the runs of the line (last, best, clean in a row, recent), «Again».
|
||||
The runs are kept by the line itself, across games.
|
||||
|
||||
## [1.3.0] — 2026-10-25
|
||||
|
||||
- Play against the computer (desktop): «♞ Play» in the library (Ctrl+G) starts a game
|
||||
|
|
|
|||
|
|
@ -51,14 +51,18 @@ Downloaded unmodified (files renamed `wk.svg` → `wK.svg`) from https://github.
|
|||
"Interface Sounds" (https://kenney.nl, CC0 1.0): leading silence trimmed, loudness matched to the
|
||||
other sets, re-encoded as Ogg Vorbis.
|
||||
|
||||
| Set | Move | Capture | Check | Checkmate | Defeat |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| wood | impactWood_light_002 | impactWood_heavy_002 | impactPlank_medium_002 | impactBell_heavy_001 | minimize_008 |
|
||||
| glass | impactGlass_light_001 | impactGlass_heavy_001 | glass_002 | impactBell_heavy_000 | minimize_004 |
|
||||
| clicks | click_002 | drop_002 | confirmation_001 | maximize_006 | minimize_006 |
|
||||
| Set | Move | Capture | Check | Checkmate | Defeat | Success |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| wood | impactWood_light_002 | impactWood_heavy_002 | impactPlank_medium_002 | impactBell_heavy_001 | minimize_008 | confirmation_004 |
|
||||
| glass | impactGlass_light_001 | impactGlass_heavy_001 | glass_002 | impactBell_heavy_000 | minimize_004 | confirmation_002 |
|
||||
| clicks | click_002 | drop_002 | confirmation_001 | maximize_006 | minimize_006 | confirmation_003 |
|
||||
|
||||
The Defeat sounds of the Lichess sets (`Defeat.ogg` of `public/sound/sfx`, `piano`,
|
||||
`futuristic`, `nes`, by Enigmahack, AGPLv3+) were downloaded unmodified on 2026-10-25.
|
||||
`apps/desktop/assets/sounds/common/Wrong.ogg` (a wrong move while learning an opening, every
|
||||
set) is Kenney's `error_003` of "Interface Sounds" (CC0), made the same way.
|
||||
|
||||
The Defeat and Success sounds of the Lichess sets (`Defeat.ogg` and `Victory.ogg` of
|
||||
`public/sound/sfx`, `piano`, `futuristic`, `nes`, by Enigmahack, AGPLv3+) were downloaded
|
||||
unmodified on 2026-10-25.
|
||||
|
||||
Notes:
|
||||
- Lichess keeps a set's checkmate sound as a link to its check sound; ChessPenguin plays the check
|
||||
|
|
|
|||
BIN
apps/desktop/assets/sounds/clicks/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/clicks/Success.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/common/Wrong.ogg
Normal file
BIN
apps/desktop/assets/sounds/common/Wrong.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/futuristic/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/futuristic/Success.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/glass/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/glass/Success.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/nes/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/nes/Success.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/piano/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/piano/Success.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/sfx/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/sfx/Success.ogg
Normal file
Binary file not shown.
BIN
apps/desktop/assets/sounds/wood/Success.ogg
Normal file
BIN
apps/desktop/assets/sounds/wood/Success.ogg
Normal file
Binary file not shown.
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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
|
|
@ -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)]
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ mod san;
|
|||
mod settings;
|
||||
mod settings_ui;
|
||||
mod sound;
|
||||
mod train;
|
||||
mod translate;
|
||||
mod translate_ui;
|
||||
mod update;
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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
387
apps/desktop/src/train.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -346,7 +346,7 @@ impl Game {
|
|||
|
||||
/// Applies a new command (the Attach of a freshly pushed node is already
|
||||
/// linked by `push_child`, so it is only recorded).
|
||||
fn record(&mut self, cmd: Command) {
|
||||
pub(crate) fn record(&mut self, cmd: Command) {
|
||||
if !matches!(cmd, Command::Attach { .. }) {
|
||||
self.apply(&cmd);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ pub mod edit;
|
|||
pub mod encoding;
|
||||
pub mod game;
|
||||
pub mod nag;
|
||||
pub mod paste;
|
||||
pub mod pgn;
|
||||
pub mod repair;
|
||||
pub mod start;
|
||||
|
|
|
|||
809
crates/chess-core/src/paste.rs
Normal file
809
crates/chess-core/src/paste.rs
Normal file
|
|
@ -0,0 +1,809 @@
|
|||
//! Pasting moves or a PGN game from the clipboard into a game as a variation
|
||||
//! (docs/research/paste-variation.md §4, docs/design/paste-variation.md).
|
||||
//!
|
||||
//! [`plan`] reads the text and finds where it fits without touching the game;
|
||||
//! [`Game::apply_paste`] then grafts the new moves — with their comments, NAGs and
|
||||
//! nested variations — as one undo step.
|
||||
//!
|
||||
//! What the clipboard may hold:
|
||||
//! - a PGN game (tags, or numbers from move 1): it hangs where its moves part from
|
||||
//! this game, along any branch; with no common start, where one of its positions
|
||||
//! occurs here (another move order); with neither it does not fit;
|
||||
//! - a fragment (`Nf3 d5`, `12...Rd8`, UCI `e2e4 e7e5`): after the selected move,
|
||||
//! instead of it, or at the position of its move number on the current line.
|
||||
//!
|
||||
//! Nothing is inserted when any move of the line is impossible.
|
||||
|
||||
use shakmaty::fen::Fen;
|
||||
use shakmaty::san::SanPlus;
|
||||
use shakmaty::uci::UciMove;
|
||||
use shakmaty::{Chess, Color, EnPassantMode, Position};
|
||||
|
||||
use crate::edit::{Command, EditError};
|
||||
use crate::encoding::TextEncoding;
|
||||
use crate::game::{Game, GameMove, MoveKind, NodeId, play_null};
|
||||
use crate::pgn::{parse_game_range, parse_str, scan_games};
|
||||
|
||||
/// Where and what to insert: the subtree of `source` from `from` hangs from `at`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PastePlan {
|
||||
/// The node of this game the new moves follow.
|
||||
pub at: NodeId,
|
||||
source: Game,
|
||||
from: NodeId,
|
||||
/// The variations of the pasted game this one lacks, along the way: (where here,
|
||||
/// the pasted move) — inserted too.
|
||||
extra: Vec<(NodeId, NodeId)>,
|
||||
/// `at` has no continuation: the moves continue the line instead of branching.
|
||||
pub continuation: bool,
|
||||
/// The moves of the new line (its main line): number, side, SAN.
|
||||
pub line: Vec<(u32, Color, String)>,
|
||||
/// The game reached this position by another move order: those moves
|
||||
/// (`1.Nf3 c5 2.e4`), noted before the first move of the line.
|
||||
pub transposition: Option<String>,
|
||||
/// «White – Black» of the pasted game, noted after the last move of the line.
|
||||
pub source_ref: Option<String>,
|
||||
/// Games in the clipboard (the first one is pasted).
|
||||
pub games: usize,
|
||||
}
|
||||
|
||||
/// Why nothing is pasted.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PasteError {
|
||||
/// The clipboard is empty or holds no moves.
|
||||
NoMoves,
|
||||
/// A fragment fits neither after the selected move nor instead of it (nor at
|
||||
/// its move number).
|
||||
DoesNotFit,
|
||||
/// A move in the middle of the line is impossible.
|
||||
Illegal {
|
||||
number: u32,
|
||||
side: Color,
|
||||
san: String,
|
||||
},
|
||||
/// The game shares no position with this one.
|
||||
Unrelated,
|
||||
/// All the moves are here already: the end of that line; `comments` — the
|
||||
/// pasted moves had comments or symbols (not carried over).
|
||||
AlreadyThere { at: NodeId, comments: bool },
|
||||
}
|
||||
|
||||
/// Finds where `text` fits in `target` (the user stands on `cursor`).
|
||||
pub fn plan(target: &Game, cursor: NodeId, text: &str) -> Result<PastePlan, PasteError> {
|
||||
// «12…Rd8» as the program itself writes black's moves.
|
||||
let text = text.trim().replace('…', "...");
|
||||
let text = text.as_str();
|
||||
if text.is_empty() {
|
||||
return Err(PasteError::NoMoves);
|
||||
}
|
||||
if text.starts_with('[') {
|
||||
// The games are only counted; the first one is read.
|
||||
let never = std::sync::atomic::AtomicBool::new(false);
|
||||
let entries = scan_games(text.as_bytes(), TextEncoding::Utf8, &mut |_| {}, &never)
|
||||
.unwrap_or_default();
|
||||
let source = match entries.first() {
|
||||
Some(e) => parse_game_range(
|
||||
text.as_bytes(),
|
||||
e.byte_range.clone(),
|
||||
e.first_line,
|
||||
TextEncoding::Utf8,
|
||||
),
|
||||
None => parse_str(text),
|
||||
};
|
||||
return whole_game(target, source, entries.len().max(1));
|
||||
}
|
||||
let uci = uci_moves(text);
|
||||
let number = leading_number(text);
|
||||
// «1.e4 …» from the standard start: a game, with all its rules (a «1.d4» into a
|
||||
// Sicilian is refused, not hung at the start).
|
||||
if uci.is_none() && number == Some((1, Color::White)) && target.start().is_standard() {
|
||||
return whole_game(target, parse_str(text), 1);
|
||||
}
|
||||
// A fragment: after the selected move, instead of it, at its move number.
|
||||
let mut candidates = vec![cursor];
|
||||
if let Some(parent) = target.parent(cursor) {
|
||||
candidates.push(parent);
|
||||
}
|
||||
if let Some(n) = number
|
||||
&& let Some(at) = by_number(target, cursor, n)
|
||||
&& !candidates.contains(&at)
|
||||
{
|
||||
candidates.push(at);
|
||||
}
|
||||
for at in candidates {
|
||||
let Some(pos) = target.position(at) else {
|
||||
continue;
|
||||
};
|
||||
if number.is_some_and(|(n, side)| (pos.fullmoves().get(), pos.turn()) != (n, side)) {
|
||||
continue;
|
||||
}
|
||||
let movetext = match &uci {
|
||||
Some(moves) => match uci_to_san(pos, moves) {
|
||||
Ok(san) => san,
|
||||
Err(0) => continue,
|
||||
Err(k) => return Err(illegal_at(pos, moves, k)),
|
||||
},
|
||||
None => text.to_owned(),
|
||||
};
|
||||
let fen = target.fen(at).unwrap_or_default();
|
||||
let source = parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n{movetext}\n")).game;
|
||||
if source.main_child(NodeId::ROOT).is_none() {
|
||||
continue; // its first move is impossible here
|
||||
}
|
||||
if let Some(e) = illegal_in_main_line(&source) {
|
||||
return Err(e);
|
||||
}
|
||||
return from_node(target, at, &source, NodeId::ROOT, None, 1);
|
||||
}
|
||||
// Numbers or not, plain SAN may still be a game from the start.
|
||||
if uci.is_none() && number.is_none() {
|
||||
return match whole_game(target, parse_str(text), 1) {
|
||||
Err(PasteError::Unrelated | PasteError::NoMoves) => Err(PasteError::DoesNotFit),
|
||||
other => other,
|
||||
};
|
||||
}
|
||||
Err(PasteError::DoesNotFit)
|
||||
}
|
||||
|
||||
/// A whole game: where its moves part from this game; else where one of its
|
||||
/// positions occurs here; else it does not fit.
|
||||
fn whole_game(
|
||||
target: &Game,
|
||||
parsed: crate::pgn::ParsedGame,
|
||||
games: usize,
|
||||
) -> Result<PastePlan, PasteError> {
|
||||
let source = parsed.game;
|
||||
if source.main_child(NodeId::ROOT).is_none() {
|
||||
return Err(PasteError::NoMoves);
|
||||
}
|
||||
if let Some(e) = illegal_in_main_line(&source) {
|
||||
return Err(e);
|
||||
}
|
||||
let same_start = key(source.start().position()) == key(target.start().position());
|
||||
// An empty game takes it all.
|
||||
if same_start && target.main_child(NodeId::ROOT).is_none() {
|
||||
return from_node(target, NodeId::ROOT, &source, NodeId::ROOT, None, games);
|
||||
}
|
||||
// The moves in common, along any branch.
|
||||
if same_start && walk(target, NodeId::ROOT, &source, NodeId::ROOT).matched > 0 {
|
||||
return from_node(target, NodeId::ROOT, &source, NodeId::ROOT, None, games);
|
||||
}
|
||||
// Another move order: the first of its positions that occurs here.
|
||||
let mut path = vec![NodeId::ROOT];
|
||||
path.extend(source.mainline());
|
||||
let targets: Vec<NodeId> = std::iter::once(NodeId::ROOT)
|
||||
.chain(target.mainline())
|
||||
.chain(target.attached_nodes())
|
||||
.collect();
|
||||
for (k, &s) in path.iter().enumerate() {
|
||||
if k == 0 && same_start {
|
||||
continue;
|
||||
}
|
||||
let Some(sp) = source.position(s) else {
|
||||
continue;
|
||||
};
|
||||
let want = key(sp);
|
||||
let Some(&t) = targets
|
||||
.iter()
|
||||
.find(|&&t| target.position(t).is_some_and(|tp| key(tp) == want))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let note = (k > 0).then(|| line_text(&source, &path[1..=k]));
|
||||
return from_node(target, t, &source, s, note, games);
|
||||
}
|
||||
Err(PasteError::Unrelated)
|
||||
}
|
||||
|
||||
/// The plan for the moves of `source` after `s`, matched along `target` from `t`.
|
||||
fn from_node(
|
||||
target: &Game,
|
||||
t: NodeId,
|
||||
source: &Game,
|
||||
s: NodeId,
|
||||
transposition: Option<String>,
|
||||
games: usize,
|
||||
) -> Result<PastePlan, PasteError> {
|
||||
let Walk {
|
||||
last,
|
||||
next,
|
||||
mut extra,
|
||||
..
|
||||
} = walk(target, t, source, s);
|
||||
// The main line is all here: its variations this game lacks may still be new.
|
||||
let (at, from) = match next {
|
||||
Some(from) => (last, from),
|
||||
None if !extra.is_empty() => extra.remove(0),
|
||||
None => {
|
||||
let comments = commented(source, s);
|
||||
return Err(PasteError::AlreadyThere { at: last, comments });
|
||||
}
|
||||
};
|
||||
let mut line = Vec::new();
|
||||
let mut cur = Some(from);
|
||||
while let Some(c) = cur {
|
||||
if let (Some(before), Some(mv)) = (source.position_before(c), source.game_move(c)) {
|
||||
line.push((before.fullmoves().get(), before.turn(), mv.san.clone()));
|
||||
}
|
||||
cur = source.main_child(c);
|
||||
}
|
||||
let name = |tag: &str| {
|
||||
source
|
||||
.tag(tag)
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty() && *v != "?")
|
||||
};
|
||||
let source_ref = match (name("White"), name("Black")) {
|
||||
(None, None) => None,
|
||||
(w, b) => Some(format!("{} – {}", w.unwrap_or("?"), b.unwrap_or("?"))),
|
||||
};
|
||||
Ok(PastePlan {
|
||||
at,
|
||||
source: source.clone(),
|
||||
from,
|
||||
extra,
|
||||
continuation: target.children(at).is_empty(),
|
||||
line,
|
||||
transposition,
|
||||
source_ref,
|
||||
games,
|
||||
})
|
||||
}
|
||||
|
||||
/// What [`walk`] found.
|
||||
struct Walk {
|
||||
/// The last node in common.
|
||||
last: NodeId,
|
||||
/// The first move of the pasted main line that is not here.
|
||||
next: Option<NodeId>,
|
||||
/// How many moves matched.
|
||||
matched: usize,
|
||||
/// The pasted game's alternatives along the way that are not here: (where here,
|
||||
/// the pasted move).
|
||||
extra: Vec<(NodeId, NodeId)>,
|
||||
}
|
||||
|
||||
/// Follows the main line of `source` from `s` through `target` from `t` while the
|
||||
/// moves are there (by any branch).
|
||||
fn walk(target: &Game, mut t: NodeId, source: &Game, mut s: NodeId) -> Walk {
|
||||
let child = |t: NodeId, kind: MoveKind| {
|
||||
target
|
||||
.children(t)
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|&c| target.game_move(c).is_some_and(|m| m.kind == kind))
|
||||
};
|
||||
let mut matched = 0;
|
||||
let mut extra = Vec::new();
|
||||
while let Some(next) = source.main_child(s) {
|
||||
// The pasted game's variations here: kept unless this game has the move.
|
||||
for &alt in &source.children(s)[1..] {
|
||||
if let Some(kind) = source.game_move(alt).map(|m| m.kind)
|
||||
&& child(t, kind).is_none()
|
||||
{
|
||||
extra.push((t, alt));
|
||||
}
|
||||
}
|
||||
let Some(kind) = source.game_move(next).map(|m| m.kind) else {
|
||||
break;
|
||||
};
|
||||
match child(t, kind) {
|
||||
Some(c) => {
|
||||
t = c;
|
||||
s = next;
|
||||
matched += 1;
|
||||
}
|
||||
None => {
|
||||
return Walk {
|
||||
last: t,
|
||||
next: Some(next),
|
||||
matched,
|
||||
extra,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Walk {
|
||||
last: t,
|
||||
next: None,
|
||||
matched,
|
||||
extra,
|
||||
}
|
||||
}
|
||||
|
||||
/// The moves walked from `s` on had comments or symbols (lost when all are here).
|
||||
fn commented(source: &Game, s: NodeId) -> bool {
|
||||
let mut cur = source.main_child(s);
|
||||
while let Some(c) = cur {
|
||||
if let Some(n) = source.node(c)
|
||||
&& (!n.nags().is_empty()
|
||||
|| !n.comments_after().is_empty()
|
||||
|| !n.comments_before().is_empty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
cur = source.main_child(c);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// An impossible move on the main line of a parsed game (its variations may keep
|
||||
/// raw text: it is carried over as it is).
|
||||
fn illegal_in_main_line(source: &Game) -> Option<PasteError> {
|
||||
let mut main = vec![NodeId::ROOT];
|
||||
main.extend(source.mainline());
|
||||
let last = *main.last()?;
|
||||
let node = source.node(last)?;
|
||||
let raw = node.unparsed().first()?;
|
||||
// The first move word, without a number glued to it («3.Qh8»).
|
||||
let san = raw
|
||||
.split_whitespace()
|
||||
.find(|w| !is_number(w))?
|
||||
.trim_start_matches(|c: char| c.is_ascii_digit() || c == '.' || c == '…')
|
||||
.to_owned();
|
||||
let pos = source.position(last)?;
|
||||
Some(PasteError::Illegal {
|
||||
number: pos.fullmoves().get(),
|
||||
side: pos.turn(),
|
||||
san,
|
||||
})
|
||||
}
|
||||
|
||||
/// The position key: pieces, side to move, castling, en passant (no counters).
|
||||
fn key(pos: &Chess) -> String {
|
||||
Fen::from_position(pos, EnPassantMode::Legal)
|
||||
.to_string()
|
||||
.split(' ')
|
||||
.take(4)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// `1.Nf3 c5 2.e4` for the given nodes of `game`.
|
||||
fn line_text(game: &Game, nodes: &[NodeId]) -> String {
|
||||
let mut out = String::new();
|
||||
for (i, &n) in nodes.iter().enumerate() {
|
||||
let (Some(before), Some(mv)) = (game.position_before(n), game.game_move(n)) else {
|
||||
continue;
|
||||
};
|
||||
let num = before.fullmoves().get();
|
||||
if !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
match before.turn() {
|
||||
Color::White => out.push_str(&format!("{num}.{}", mv.san)),
|
||||
Color::Black if i == 0 => out.push_str(&format!("{num}...{}", mv.san)),
|
||||
Color::Black => out.push_str(&mv.san),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The number of a move (`12.`, `12...`, `12…`), as a word of the text.
|
||||
fn is_number(w: &str) -> bool {
|
||||
let digits = w.trim_end_matches(['.', '…']);
|
||||
!digits.is_empty() && digits.len() < w.len() && digits.chars().all(|c| c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// `12.` → (12, White), `12...` / `12…` → (12, Black), when the text starts so.
|
||||
fn leading_number(text: &str) -> Option<(u32, Color)> {
|
||||
let first = text.split_whitespace().next()?;
|
||||
let digits: String = first.chars().take_while(char::is_ascii_digit).collect();
|
||||
let rest = &first[digits.len()..];
|
||||
let n: u32 = digits.parse().ok()?;
|
||||
if rest.starts_with("...") || rest.starts_with('…') {
|
||||
Some((n, Color::Black))
|
||||
} else if rest.starts_with('.') {
|
||||
Some((n, Color::White))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The words of a UCI line (`e2e4 e7e5 g1f3`, numbers allowed), if the text is one.
|
||||
fn uci_moves(text: &str) -> Option<Vec<String>> {
|
||||
let words: Vec<&str> = text
|
||||
.split_whitespace()
|
||||
.filter(|w| !is_number(w) && !matches!(*w, "1-0" | "0-1" | "1/2-1/2" | "*"))
|
||||
.collect();
|
||||
let is_uci = |w: &str| {
|
||||
let b = w.as_bytes();
|
||||
(b.len() == 4 || b.len() == 5)
|
||||
&& (b'a'..=b'h').contains(&b[0])
|
||||
&& (b'1'..=b'8').contains(&b[1])
|
||||
&& (b'a'..=b'h').contains(&b[2])
|
||||
&& (b'1'..=b'8').contains(&b[3])
|
||||
&& (b.len() == 4 || b"qrbn".contains(&b[4]))
|
||||
};
|
||||
(!words.is_empty() && words.iter().all(|w| is_uci(w)))
|
||||
.then(|| words.iter().map(|w| (*w).to_owned()).collect())
|
||||
}
|
||||
|
||||
/// UCI moves played from `pos` as SAN; `Err(k)`: the `k`-th move is impossible.
|
||||
fn uci_to_san(pos: &Chess, moves: &[String]) -> Result<String, usize> {
|
||||
let mut pos = pos.clone();
|
||||
let mut out = Vec::new();
|
||||
for (k, w) in moves.iter().enumerate() {
|
||||
let m = w
|
||||
.parse::<UciMove>()
|
||||
.ok()
|
||||
.and_then(|u| u.to_move(&pos).ok())
|
||||
.ok_or(k)?;
|
||||
out.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string());
|
||||
}
|
||||
Ok(out.join(" "))
|
||||
}
|
||||
|
||||
/// The error for the `k`-th UCI move from `pos`.
|
||||
fn illegal_at(pos: &Chess, moves: &[String], k: usize) -> PasteError {
|
||||
let mut pos = pos.clone();
|
||||
for w in &moves[..k] {
|
||||
if let Some(m) = w.parse::<UciMove>().ok().and_then(|u| u.to_move(&pos).ok()) {
|
||||
pos.play_unchecked(m);
|
||||
}
|
||||
}
|
||||
PasteError::Illegal {
|
||||
number: pos.fullmoves().get(),
|
||||
side: pos.turn(),
|
||||
san: moves[k].clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The node of the current line (the path to `cursor`, then on by the main line)
|
||||
/// where the move of number `n` is to be made.
|
||||
fn by_number(target: &Game, cursor: NodeId, (n, side): (u32, Color)) -> Option<NodeId> {
|
||||
let mut line = target.path(cursor);
|
||||
let mut cur = cursor;
|
||||
while let Some(next) = target.main_child(cur) {
|
||||
line.push(next);
|
||||
cur = next;
|
||||
}
|
||||
line.into_iter().find(|&id| {
|
||||
target
|
||||
.position(id)
|
||||
.is_some_and(|p| (p.fullmoves().get(), p.turn()) == (n, side))
|
||||
})
|
||||
}
|
||||
|
||||
impl Game {
|
||||
/// Inserts what [`plan`] found: the new moves with their comments, symbols and
|
||||
/// variations, the move-order note and the source, as one undo step. Returns the
|
||||
/// first inserted node.
|
||||
pub fn apply_paste(&mut self, plan: &PastePlan) -> Result<NodeId, EditError> {
|
||||
let pos = self
|
||||
.position(plan.at)
|
||||
.ok_or(EditError::UnknownNode)?
|
||||
.clone();
|
||||
// Every move is checked before the game changes.
|
||||
check(&plan.source, plan.from, &pos)?;
|
||||
for &(at, from) in &plan.extra {
|
||||
let pos = self.position(at).ok_or(EditError::UnknownNode)?.clone();
|
||||
check(&plan.source, from, &pos)?;
|
||||
}
|
||||
self.edit_group(|g| g.paste_grafts(plan))
|
||||
}
|
||||
|
||||
/// The grafts of [`Game::apply_paste`], checked already.
|
||||
fn paste_grafts(&mut self, plan: &PastePlan) -> Result<NodeId, EditError> {
|
||||
let first = self.graft(plan.at, &plan.source, plan.from)?;
|
||||
if let Some(note) = &plan.transposition
|
||||
&& let Some(n) = self.node_mut(first)
|
||||
{
|
||||
n.comments_before.insert(0, note.clone());
|
||||
}
|
||||
if let Some(r) = &plan.source_ref {
|
||||
let end = self.line_end(first);
|
||||
if let Some(n) = self.node_mut(end) {
|
||||
n.comments_after.push(r.clone());
|
||||
}
|
||||
}
|
||||
let index = self.child_index(first).unwrap_or(0);
|
||||
self.record(Command::Attach {
|
||||
parent: plan.at,
|
||||
child: first,
|
||||
index,
|
||||
});
|
||||
for &(at, from) in &plan.extra {
|
||||
let id = self.graft(at, &plan.source, from)?;
|
||||
let index = self.child_index(id).unwrap_or(0);
|
||||
self.record(Command::Attach {
|
||||
parent: at,
|
||||
child: id,
|
||||
index,
|
||||
});
|
||||
}
|
||||
Ok(first)
|
||||
}
|
||||
|
||||
/// Copies the subtree of `source` from `s` under `parent`, positions replayed
|
||||
/// here (the counters may differ from the source's).
|
||||
fn graft(&mut self, parent: NodeId, source: &Game, s: NodeId) -> Result<NodeId, EditError> {
|
||||
let pos = self.position(parent).ok_or(EditError::UnknownNode)?.clone();
|
||||
let node = source.node(s).ok_or(EditError::UnknownNode)?;
|
||||
let mv = node.game_move().ok_or(EditError::UnknownNode)?;
|
||||
let (gm, after) = play(&pos, mv)?;
|
||||
let id = self.push_child(parent, gm, after);
|
||||
if let Some(n) = self.node_mut(id) {
|
||||
n.nags = node.nags().to_vec();
|
||||
n.comments_before = node.comments_before().to_vec();
|
||||
n.comments_after = node.comments_after().to_vec();
|
||||
n.unparsed = node.unparsed().to_vec();
|
||||
}
|
||||
for &c in source.children(s) {
|
||||
self.graft(id, source, c)?;
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The move `mv` from `pos`: the node's move and the position after it.
|
||||
fn play(pos: &Chess, mv: &GameMove) -> Result<(GameMove, Chess), EditError> {
|
||||
match mv.kind {
|
||||
MoveKind::Normal(m) => {
|
||||
if !pos.is_legal(m) {
|
||||
return Err(EditError::IllegalMove(mv.san.clone()));
|
||||
}
|
||||
let mut after = pos.clone();
|
||||
let san = SanPlus::from_move_and_play_unchecked(&mut after, m).to_string();
|
||||
Ok((GameMove { kind: mv.kind, san }, after))
|
||||
}
|
||||
MoveKind::Null => {
|
||||
let after = play_null(pos).map_err(|_| EditError::IllegalMove("--".into()))?;
|
||||
Ok((
|
||||
GameMove {
|
||||
kind: MoveKind::Null,
|
||||
san: "--".into(),
|
||||
},
|
||||
after,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every move of the subtree of `source` from `s` can be made from `pos`.
|
||||
fn check(source: &Game, s: NodeId, pos: &Chess) -> Result<(), EditError> {
|
||||
let mut stack = vec![(s, pos.clone())];
|
||||
while let Some((id, pos)) = stack.pop() {
|
||||
let mv = source.game_move(id).ok_or(EditError::UnknownNode)?;
|
||||
let (_, after) = play(&pos, mv)?;
|
||||
for &c in source.children(id) {
|
||||
stack.push((c, after.clone()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn game(pgn: &str) -> Game {
|
||||
parse_str(pgn).game
|
||||
}
|
||||
|
||||
/// The node reached by the SAN moves from the root (along any branch).
|
||||
fn at(g: &Game, sans: &[&str]) -> NodeId {
|
||||
let mut cur = NodeId::ROOT;
|
||||
for s in sans {
|
||||
cur = *g
|
||||
.children(cur)
|
||||
.iter()
|
||||
.find(|&&c| g.game_move(c).is_some_and(|m| m.san == *s))
|
||||
.unwrap_or_else(|| panic!("no {s}"));
|
||||
}
|
||||
cur
|
||||
}
|
||||
|
||||
fn sans(p: &PastePlan) -> Vec<&str> {
|
||||
p.line.iter().map(|(_, _, s)| s.as_str()).collect()
|
||||
}
|
||||
|
||||
const SICILIAN: &str = "1. e4 c5 2. Nf3 d6 3. d4 *";
|
||||
|
||||
#[test]
|
||||
fn a_game_hangs_where_it_parts_and_undoes_whole() {
|
||||
let mut g = game(SICILIAN);
|
||||
let before = g.canonical_tree();
|
||||
let cursor = at(&g, &["e4", "c5", "Nf3", "d6", "d4"]);
|
||||
let p = plan(&g, cursor, "1.e4 c5 2.Nf3 Nc6 3.d4").unwrap();
|
||||
assert_eq!(p.at, at(&g, &["e4", "c5", "Nf3"]));
|
||||
assert_eq!(sans(&p), ["Nc6", "d4"]);
|
||||
assert!(!p.continuation);
|
||||
let first = g.apply_paste(&p).unwrap();
|
||||
assert_eq!(g.game_move(first).unwrap().san, "Nc6");
|
||||
// The main line is the same; the variation is the last child.
|
||||
assert_eq!(g.mainline().len(), 5);
|
||||
assert_eq!(g.children(p.at).last(), Some(&first));
|
||||
g.undo();
|
||||
assert_eq!(g.canonical_tree(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_game_is_refused() {
|
||||
let g = game(SICILIAN);
|
||||
let cursor = at(&g, &["e4", "c5"]);
|
||||
assert_eq!(
|
||||
plan(&g, cursor, "1.d4 d5 2.c4").unwrap_err(),
|
||||
PasteError::Unrelated
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&g, cursor, "[White \"A\"]\n[Black \"B\"]\n\n1.d4 d5 2.c4 *").unwrap_err(),
|
||||
PasteError::Unrelated
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_move_order_is_found_and_noted() {
|
||||
let g = game(SICILIAN);
|
||||
let cursor = at(&g, &["e4", "c5", "Nf3"]);
|
||||
// All there by another order.
|
||||
assert!(matches!(
|
||||
plan(&g, cursor, "1.Nf3 c5 2.e4 d6 3.d4").unwrap_err(),
|
||||
PasteError::AlreadyThere { .. }
|
||||
));
|
||||
let p = plan(&g, cursor, "1.Nf3 c5 2.e4 Nc6").unwrap();
|
||||
assert_eq!(p.at, at(&g, &["e4", "c5", "Nf3"]));
|
||||
assert_eq!(sans(&p), ["Nc6"]);
|
||||
assert_eq!(p.transposition.as_deref(), Some("1.Nf3 c5 2.e4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragments_after_instead_of_or_by_number() {
|
||||
let g = game("1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. f3 Bf5 6. Ng3 *");
|
||||
let bf5 = at(
|
||||
&g,
|
||||
&[
|
||||
"e4", "c6", "d4", "d5", "Nc3", "dxe4", "Nxe4", "Nf6", "f3", "Bf5",
|
||||
],
|
||||
);
|
||||
// Instead of the selected move.
|
||||
let p = plan(&g, bf5, "5...Nxe4 6.fxe4").unwrap();
|
||||
assert_eq!(p.at, g.parent(bf5).unwrap());
|
||||
assert_eq!(sans(&p), ["Nxe4", "fxe4"]);
|
||||
// After it.
|
||||
let p = plan(&g, bf5, "6.Qd3 e6").unwrap();
|
||||
assert_eq!(p.at, bf5);
|
||||
// Without numbers.
|
||||
let p = plan(&g, bf5, "Qd3 e6").unwrap();
|
||||
assert_eq!(p.at, bf5);
|
||||
// By the number on the current line.
|
||||
let e4 = at(&g, &["e4"]);
|
||||
let p = plan(&g, e4, "4...e5").unwrap();
|
||||
assert_eq!(
|
||||
p.at,
|
||||
at(&g, &["e4", "c6", "d4", "d5", "Nc3", "dxe4", "Nxe4"])
|
||||
);
|
||||
// Nowhere.
|
||||
assert_eq!(plan(&g, bf5, "Ke3").unwrap_err(), PasteError::DoesNotFit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uci_lines_and_impossible_moves() {
|
||||
let g = Game::new();
|
||||
let p = plan(&g, NodeId::ROOT, "e2e4 e7e5 g1f3").unwrap();
|
||||
assert_eq!(sans(&p), ["e4", "e5", "Nf3"]);
|
||||
assert!(p.continuation);
|
||||
assert_eq!(
|
||||
plan(&g, NodeId::ROOT, "e2e4 e7e5 e1e3").unwrap_err(),
|
||||
PasteError::Illegal {
|
||||
number: 2,
|
||||
side: Color::White,
|
||||
san: "e1e3".into()
|
||||
}
|
||||
);
|
||||
let s = game(SICILIAN);
|
||||
assert_eq!(
|
||||
plan(&s, NodeId::ROOT, "1.e4 c5 2.Nf3 Nc6 3.Qh8").unwrap_err(),
|
||||
PasteError::Illegal {
|
||||
number: 3,
|
||||
side: Color::White,
|
||||
san: "Qh8".into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_variations_and_the_source_come_along() {
|
||||
let mut g = game(SICILIAN);
|
||||
let text = "[White \"Mellado Trivino,J\"]\n[Black \"Garcia Albarracin,F\"]\n[Result \"0-1\"]\n\n\
|
||||
1.e4 c5 2.Nf3 Nc6 {Old.} 3.d4 $1 (3.Bb5 g6) cxd4 0-1";
|
||||
let p = plan(&g, NodeId::ROOT, text).unwrap();
|
||||
assert_eq!(
|
||||
p.source_ref.as_deref(),
|
||||
Some("Mellado Trivino,J – Garcia Albarracin,F")
|
||||
);
|
||||
let first = g.apply_paste(&p).unwrap();
|
||||
let after = g.to_pgn();
|
||||
assert!(after.contains("{Old.}"), "{after}");
|
||||
assert!(after.contains("Bb5"), "{after}");
|
||||
assert_eq!(
|
||||
g.node(g.line_end(first)).unwrap().comments_after(),
|
||||
["Mellado Trivino,J – Garcia Albarracin,F"]
|
||||
);
|
||||
assert_eq!(
|
||||
g.node(at(&g, &["e4", "c5", "Nf3", "Nc6", "d4"]))
|
||||
.unwrap()
|
||||
.nags()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
// Written and read again: the same tree.
|
||||
let again = game(&after);
|
||||
assert_eq!(again.canonical_tree(), g.canonical_tree());
|
||||
assert!(g.is_attached(first));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pasted_games_variations_come_along() {
|
||||
let mut g = game(SICILIAN);
|
||||
let before = g.canonical_tree();
|
||||
// An alternative at the parting point and one on a move in common.
|
||||
let text =
|
||||
"[White \"A\"]\n[Black \"B\"]\n\n1.e4 c5 (1...e5 2.Nf3) 2.Nf3 Nc6 (2...e6 3.d4) 3.d4 *";
|
||||
let p = plan(&g, NodeId::ROOT, text).unwrap();
|
||||
g.apply_paste(&p).unwrap();
|
||||
let nf3 = at(&g, &["e4", "c5", "Nf3"]);
|
||||
let kids = |g: &Game, id| -> Vec<String> {
|
||||
g.children(id)
|
||||
.iter()
|
||||
.map(|&c| g.game_move(c).unwrap().san.clone())
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(kids(&g, nf3), ["d6", "Nc6", "e6"]);
|
||||
assert_eq!(kids(&g, at(&g, &["e4"])), ["c5", "e5"]);
|
||||
// One undo step for all of it.
|
||||
g.undo();
|
||||
assert_eq!(g.canonical_tree(), before);
|
||||
// Only a variation is new: it is pasted, not «already there».
|
||||
let p = plan(&g, NodeId::ROOT, "1.e4 c5 (1...e6) 2.Nf3 d6 3.d4").unwrap();
|
||||
assert_eq!(p.at, at(&g, &["e4"]));
|
||||
assert_eq!(sans(&p), ["e6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_numbers_with_an_ellipsis_character() {
|
||||
let g = game(SICILIAN);
|
||||
let p = plan(&g, at(&g, &["e4"]), "1…e5 2.Nf3").unwrap();
|
||||
assert_eq!(sans(&p), ["e5", "Nf3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_game_or_line_is_already_there() {
|
||||
let g = game(SICILIAN);
|
||||
match plan(&g, NodeId::ROOT, SICILIAN).unwrap_err() {
|
||||
PasteError::AlreadyThere { at: end, comments } => {
|
||||
assert_eq!(end, *g.mainline().last().unwrap());
|
||||
assert!(!comments);
|
||||
}
|
||||
e => panic!("{e:?}"),
|
||||
}
|
||||
assert!(matches!(
|
||||
plan(&g, NodeId::ROOT, "1.e4 c5 {Sicilian}").unwrap_err(),
|
||||
PasteError::AlreadyThere { comments: true, .. }
|
||||
));
|
||||
assert_eq!(
|
||||
plan(&g, NodeId::ROOT, " ").unwrap_err(),
|
||||
PasteError::NoMoves
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_from_a_position_with_fullmove_zero() {
|
||||
let fen = "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0";
|
||||
let mut g = game(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. e4 Kd7 *"));
|
||||
let e4 = at(&g, &["e4"]);
|
||||
let p = plan(&g, e4, "1...Ke7").unwrap();
|
||||
assert_eq!(p.at, e4);
|
||||
g.apply_paste(&p).unwrap();
|
||||
assert_eq!(g.children(e4).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_games_paste_the_first() {
|
||||
let g = game(SICILIAN);
|
||||
let text = "[White \"A\"]\n\n1.e4 c5 2.Nf3 Nc6 *\n\n[White \"B\"]\n\n1.e4 e5 *\n";
|
||||
let p = plan(&g, NodeId::ROOT, text).unwrap();
|
||||
assert_eq!(p.games, 2);
|
||||
assert_eq!(sans(&p), ["Nc6"]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Loading…
Add table
Add a link
Reference in a new issue