feat: simplify opening variation training
This commit is contained in:
parent
f49aab68fa
commit
71ca5ad9e6
14 changed files with 1571 additions and 637 deletions
|
|
@ -4,6 +4,13 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
- Desktop opening training: collect PGN repertoires, add a line from a game, and practise
|
||||
for White, Black or both sides. Variations are dealt in random cycles without repeating
|
||||
a full route; a route can start with automatic context, and its result offers both
|
||||
«Next variation» and «Repeat path». Depth, scope and separate-position review controls
|
||||
have been removed; the library shows the actual number of variations. The training
|
||||
screen has no move list; previously shown positions can still be reviewed on the board.
|
||||
|
||||
## [2.1.5] — 2026-11-02
|
||||
|
||||
- Preparing against an opponent is saved by itself: a preparation appears in the
|
||||
|
|
|
|||
|
|
@ -16266,6 +16266,17 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Ikkala tomon",
|
||||
"Екі тарап",
|
||||
],
|
||||
[
|
||||
"Variants",
|
||||
"Варианты",
|
||||
"Variantes",
|
||||
"Varianten",
|
||||
"Variantes",
|
||||
"Varianti",
|
||||
"Variantes",
|
||||
"Variantlar",
|
||||
"Варианттар",
|
||||
],
|
||||
[
|
||||
"No targets in this mode",
|
||||
"В этом режиме нет целей",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::time::Duration;
|
||||
use std::{sync::mpsc, time::Duration};
|
||||
|
||||
use chess_core::shakmaty::{Chess, Color, Move, Position, Square, uci::UciMove};
|
||||
use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2};
|
||||
|
|
@ -28,10 +28,17 @@ struct Flash {
|
|||
wrong: bool,
|
||||
}
|
||||
|
||||
struct NextPathJob {
|
||||
generation: u64,
|
||||
rx: mpsc::Receiver<(u64, Result<TrainingSession, String>)>,
|
||||
}
|
||||
|
||||
pub struct TrainingUi {
|
||||
repertoire: Repertoire,
|
||||
saved_stats: StatsData,
|
||||
discard_requested: bool,
|
||||
next_job: Option<NextPathJob>,
|
||||
next_generation: u64,
|
||||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
policy: SrsPolicy,
|
||||
|
|
@ -71,7 +78,55 @@ impl TrainingUi {
|
|||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new_random(
|
||||
repertoire: &Repertoire,
|
||||
mode: TrainingMode,
|
||||
stats: StatsData,
|
||||
store: StatsStore,
|
||||
flipped: bool,
|
||||
) -> Result<Self, SessionError> {
|
||||
let session = TrainingSession::new_random(repertoire, mode, stats, now())?;
|
||||
let task_origin = if session.scope().include_context {
|
||||
repertoire.game().start().position().clone()
|
||||
} else {
|
||||
session.scope_start_position().clone()
|
||||
};
|
||||
let mut training = Self {
|
||||
repertoire: repertoire.clone(),
|
||||
saved_stats: session.stats().clone(),
|
||||
discard_requested: false,
|
||||
next_job: None,
|
||||
next_generation: 0,
|
||||
mode,
|
||||
queue_mode: QueueMode::Practice,
|
||||
policy: SrsPolicy::Due,
|
||||
session,
|
||||
store,
|
||||
board: BoardState::default(),
|
||||
flipped: match mode {
|
||||
TrainingMode::White => false,
|
||||
TrainingMode::Black => true,
|
||||
TrainingMode::Both => flipped,
|
||||
},
|
||||
positions: Vec::new(),
|
||||
position_path_len: usize::MAX,
|
||||
position_task_start: usize::MAX,
|
||||
task_start: 0,
|
||||
task_origin,
|
||||
view_ply: 0,
|
||||
flash: None,
|
||||
hint: None,
|
||||
message: None,
|
||||
save_error: None,
|
||||
confirm_discard: false,
|
||||
completed_targets: 0,
|
||||
target_limit: usize::MAX,
|
||||
};
|
||||
training.save();
|
||||
Ok(training)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments, dead_code)]
|
||||
pub fn new_with_policy(
|
||||
repertoire: &Repertoire,
|
||||
scope: TrainingScope,
|
||||
|
|
@ -98,6 +153,8 @@ impl TrainingUi {
|
|||
repertoire: repertoire.clone(),
|
||||
saved_stats,
|
||||
discard_requested: false,
|
||||
next_job: None,
|
||||
next_generation: 0,
|
||||
mode,
|
||||
queue_mode,
|
||||
policy,
|
||||
|
|
@ -200,7 +257,11 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn play(&mut self, mv: Move) {
|
||||
if self.is_finished() || self.flash.is_some() || self.save_error.is_some() {
|
||||
if self.is_finished()
|
||||
|| self.flash.is_some()
|
||||
|| self.save_error.is_some()
|
||||
|| self.next_job.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut after = self.session.position().clone();
|
||||
|
|
@ -247,7 +308,7 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn restart(&mut self) {
|
||||
if self.save_error.is_some() {
|
||||
if self.save_error.is_some() || self.next_job.is_some() {
|
||||
return;
|
||||
}
|
||||
match self.session.restart(now()) {
|
||||
|
|
@ -257,15 +318,81 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn next_path(&mut self) {
|
||||
if self.save_error.is_some() || !self.is_path_practice() {
|
||||
if self.save_error.is_some() || self.next_job.is_some() || !self.is_path_practice() {
|
||||
return;
|
||||
}
|
||||
match self.session.next_path(now()) {
|
||||
Ok(()) => self.after_run_reset(),
|
||||
let prepared = match self.session.prepare_next_path() {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => {
|
||||
self.message = Some(error.to_string());
|
||||
return;
|
||||
}
|
||||
};
|
||||
let repertoire = self.repertoire.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.next_generation = self.next_generation.wrapping_add(1);
|
||||
let generation = self.next_generation;
|
||||
self.next_job = Some(NextPathJob { generation, rx });
|
||||
if let Err(error) = crate::platform::spawn("repertoire-training-next", move || {
|
||||
let result = prepared
|
||||
.run(&repertoire, now())
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = tx.send((generation, result));
|
||||
}) {
|
||||
self.next_job = None;
|
||||
self.message = Some(error.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_next(&mut self) {
|
||||
let (generation, result) = {
|
||||
let Some(job) = &self.next_job else {
|
||||
return;
|
||||
};
|
||||
match job.rx.try_recv() {
|
||||
Ok(result) => result,
|
||||
Err(mpsc::TryRecvError::Empty) => return,
|
||||
Err(mpsc::TryRecvError::Disconnected) => (
|
||||
job.generation,
|
||||
Err("next-path worker stopped without a result".to_owned()),
|
||||
),
|
||||
}
|
||||
};
|
||||
self.apply_next(generation, result);
|
||||
}
|
||||
|
||||
fn apply_next(&mut self, generation: u64, result: Result<TrainingSession, String>) {
|
||||
if generation != self.next_generation
|
||||
|| self
|
||||
.next_job
|
||||
.as_ref()
|
||||
.is_none_or(|job| job.generation != generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.next_job = None;
|
||||
match result {
|
||||
Ok(session) => {
|
||||
self.session = session;
|
||||
self.after_run_reset();
|
||||
self.save();
|
||||
}
|
||||
Err(error) => self.message = Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn deliver_next(&mut self) {
|
||||
let (generation, result) = self
|
||||
.next_job
|
||||
.as_ref()
|
||||
.expect("a pending next-path job")
|
||||
.rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("next-path worker result");
|
||||
self.apply_next(generation, result);
|
||||
}
|
||||
|
||||
fn after_run_reset(&mut self) {
|
||||
self.completed_targets = 0;
|
||||
self.target_limit = target_count(
|
||||
|
|
@ -314,7 +441,7 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn keyboard(&mut self, ui: &Ui, actions: &mut Vec<TrainingAction>) {
|
||||
if ui.ctx().egui_wants_keyboard_input() {
|
||||
if ui.ctx().egui_wants_keyboard_input() || self.next_job.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut command = None;
|
||||
|
|
@ -423,6 +550,7 @@ impl TrainingUi {
|
|||
interactive: !self.is_finished()
|
||||
&& self.flash.is_none()
|
||||
&& self.save_error.is_none()
|
||||
&& self.next_job.is_none()
|
||||
&& self.view_ply + 1 == self.positions.len(),
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
|
|
@ -523,6 +651,15 @@ impl TrainingUi {
|
|||
});
|
||||
}
|
||||
|
||||
fn preparing(&self, ui: &mut Ui) {
|
||||
card(ui, false).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui.label(tr("Preparing the tree…"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn result(&mut self, ui: &mut Ui, actions: &mut Vec<TrainingAction>) {
|
||||
card(ui, false).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
|
|
@ -535,6 +672,9 @@ impl TrainingUi {
|
|||
.strong()
|
||||
.size(17.0),
|
||||
);
|
||||
if let Some(message) = &self.message {
|
||||
ui.label(message);
|
||||
}
|
||||
if self.is_path_practice() {
|
||||
let played = self
|
||||
.session
|
||||
|
|
@ -591,94 +731,6 @@ impl TrainingUi {
|
|||
});
|
||||
}
|
||||
|
||||
fn notation(&mut self, ui: &mut Ui) {
|
||||
let mut clicked = None;
|
||||
let mut marks: std::collections::HashMap<(String, String), (u32, bool)> =
|
||||
std::collections::HashMap::new();
|
||||
for attempt in self.session.attempts() {
|
||||
let mark = marks
|
||||
.entry((
|
||||
attempt.position_fen4.clone(),
|
||||
if self.mode == TrainingMode::Both {
|
||||
String::new()
|
||||
} else {
|
||||
attempt.expected_uci.clone()
|
||||
},
|
||||
))
|
||||
.or_default();
|
||||
mark.0 += u32::from(!attempt.correct);
|
||||
mark.1 |= attempt.hinted;
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
let path = &self.session.path()[self.task_start..];
|
||||
let mut index = 0;
|
||||
while index < path.len() {
|
||||
let white = self
|
||||
.positions
|
||||
.get(index)
|
||||
.is_some_and(|p| p.turn() == Color::White);
|
||||
let number = self.positions.get(index).map_or(1, |p| p.fullmoves().get());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.add_sized(
|
||||
[36.0, 24.0],
|
||||
egui::Label::new(
|
||||
RichText::new(if white {
|
||||
format!("{number}.")
|
||||
} else {
|
||||
format!("{number}…")
|
||||
})
|
||||
.weak(),
|
||||
),
|
||||
);
|
||||
for color in [Color::White, Color::Black] {
|
||||
if index >= path.len() {
|
||||
break;
|
||||
}
|
||||
let is_white = self
|
||||
.positions
|
||||
.get(index)
|
||||
.is_some_and(|p| p.turn() == Color::White);
|
||||
if is_white != (color == Color::White) {
|
||||
continue;
|
||||
}
|
||||
let played = &path[index];
|
||||
let global = self.task_start + index;
|
||||
let mut text = played.san.clone();
|
||||
if let Some((mistakes, hinted)) = marks.get(&(
|
||||
played.position_before.clone(),
|
||||
if self.mode == TrainingMode::Both {
|
||||
String::new()
|
||||
} else {
|
||||
played.uci.clone()
|
||||
},
|
||||
)) {
|
||||
if *mistakes > 0 {
|
||||
text.push_str(&format!(" ×{mistakes}"));
|
||||
}
|
||||
if *hinted {
|
||||
text.push_str(" *");
|
||||
}
|
||||
}
|
||||
let response = ui.selectable_label(self.view_ply == global + 1, text);
|
||||
let was_clicked = response.clicked();
|
||||
if played.automatic {
|
||||
response.on_hover_text(tr("Automatic move/context"));
|
||||
}
|
||||
if was_clicked {
|
||||
clicked = Some(global + 1 - self.task_start);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(ply) = clicked {
|
||||
self.view_ply = ply;
|
||||
}
|
||||
}
|
||||
|
||||
fn save_strip(&mut self, ui: &mut Ui) {
|
||||
let Some(error) = self.save_error.clone() else {
|
||||
return;
|
||||
|
|
@ -716,7 +768,11 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, settings: &Settings, name: &str) -> Vec<TrainingAction> {
|
||||
self.poll_next();
|
||||
let mut actions = Vec::new();
|
||||
if self.next_job.is_some() {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(50));
|
||||
}
|
||||
if let Some(flash) = &self.flash {
|
||||
let left = flash
|
||||
.until
|
||||
|
|
@ -731,7 +787,10 @@ impl TrainingUi {
|
|||
egui::Panel::top("repertoire_training_header").show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.button(format!("← {}", tr("Back to repertoire")))
|
||||
.add_enabled(
|
||||
self.next_job.is_none(),
|
||||
egui::Button::new(format!("← {}", tr("Back to repertoire"))),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
if self.save_error.is_some() {
|
||||
|
|
@ -765,6 +824,10 @@ impl TrainingUi {
|
|||
};
|
||||
crate::widgets::check_panel("repertoire_training_side", &side.response);
|
||||
egui::CentralPanel::default().show(ui, |ui| self.board(ui, settings, &mut actions));
|
||||
if self.next_job.is_some() {
|
||||
self.discard_requested = false;
|
||||
actions.retain(|action| !matches!(action, TrainingAction::Back));
|
||||
}
|
||||
if self.save_error.is_some() && !self.discard_requested {
|
||||
if actions
|
||||
.iter()
|
||||
|
|
@ -781,63 +844,66 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn side(&mut self, ui: &mut Ui, actions: &mut Vec<TrainingAction>) {
|
||||
let notation_height = (ui.available_height() - 230.0).max(120.0);
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_training_controls")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
self.save_strip(ui);
|
||||
if self.is_finished() {
|
||||
if self.next_job.is_some() {
|
||||
self.preparing(ui);
|
||||
} else if self.is_finished() {
|
||||
self.result(ui, actions);
|
||||
} else {
|
||||
self.task_card(ui);
|
||||
self.user_card(ui);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
for (label, ply) in [
|
||||
("⏮", 0),
|
||||
("◀", self.view_ply.saturating_sub(1)),
|
||||
(
|
||||
"▶",
|
||||
(self.view_ply + 1).min(self.positions.len().saturating_sub(1)),
|
||||
),
|
||||
("⏭", self.positions.len().saturating_sub(1)),
|
||||
] {
|
||||
if self.next_job.is_none() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
for (label, ply) in [
|
||||
("⏮", 0),
|
||||
("◀", self.view_ply.saturating_sub(1)),
|
||||
(
|
||||
"▶",
|
||||
(self.view_ply + 1).min(self.positions.len().saturating_sub(1)),
|
||||
),
|
||||
("⏭", self.positions.len().saturating_sub(1)),
|
||||
] {
|
||||
if ui
|
||||
.add_sized([30.0, 26.0], egui::Button::new(label))
|
||||
.clicked()
|
||||
{
|
||||
self.view_ply = ply;
|
||||
}
|
||||
}
|
||||
if ui
|
||||
.add_sized([30.0, 26.0], egui::Button::new(label))
|
||||
.add_sized([30.0, 26.0], egui::Button::new("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.view_ply = ply;
|
||||
self.flipped = !self.flipped;
|
||||
}
|
||||
}
|
||||
if ui
|
||||
.add_sized([30.0, 26.0], egui::Button::new("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.flipped = !self.flipped;
|
||||
}
|
||||
if !self.is_finished() && ui.button(tr("↻ Restart")).clicked() {
|
||||
self.restart();
|
||||
}
|
||||
});
|
||||
if self.view_ply + 1 < self.positions.len()
|
||||
if !self.is_finished() && ui.button(tr("↻ Restart")).clicked() {
|
||||
self.restart();
|
||||
}
|
||||
});
|
||||
}
|
||||
if self.next_job.is_none()
|
||||
&& self.view_ply + 1 < self.positions.len()
|
||||
&& ui
|
||||
.link(tr("Viewing an earlier position · back to training — End"))
|
||||
.clicked()
|
||||
{
|
||||
self.go_end();
|
||||
}
|
||||
ui.separator();
|
||||
ui.allocate_ui(vec2(ui.available_width(), notation_height), |ui| {
|
||||
self.notation(ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn debug_hint(&mut self) {
|
||||
if self.next_job.is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(candidate) = self.session.hint(now()) {
|
||||
self.hint = move_squares(&candidate);
|
||||
self.save();
|
||||
|
|
@ -848,7 +914,13 @@ impl TrainingUi {
|
|||
for text in moves.split_whitespace() {
|
||||
match text {
|
||||
"hint" => self.debug_hint(),
|
||||
"next" => self.next_path(),
|
||||
"next" => {
|
||||
self.next_path();
|
||||
#[cfg(test)]
|
||||
if self.next_job.is_some() {
|
||||
self.deliver_next();
|
||||
}
|
||||
}
|
||||
"repeat" => self.restart(),
|
||||
_ => {}
|
||||
}
|
||||
|
|
@ -1176,6 +1248,164 @@ mod tests {
|
|||
assert_board_matches_session(&training);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_next_saves_its_cursor_without_a_move_and_repeat_does_not_advance_it() {
|
||||
let fixture = training(
|
||||
"1. e4 e5 (1... c5) 2. Nf3 (2. c4) *",
|
||||
TrainingMode::Both,
|
||||
"random-cursor-save",
|
||||
);
|
||||
let mut random = TrainingUi::new_random(
|
||||
&fixture.repertoire,
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
fixture.store.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(random.save_error.is_none());
|
||||
assert_eq!(random.session.queue_mode(), QueueMode::Practice);
|
||||
let initial = serde_json::to_value(random.session.stats()).unwrap();
|
||||
assert_eq!(initial["random_practice_cursors"][0]["position"], 1);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.store.load().unwrap()).unwrap(),
|
||||
initial
|
||||
);
|
||||
|
||||
random.debug_moves("next");
|
||||
assert!(random.save_error.is_none());
|
||||
assert!(random.session.attempts().is_empty());
|
||||
assert_board_matches_session(&random);
|
||||
let next = serde_json::to_value(random.session.stats()).unwrap();
|
||||
assert_eq!(next["random_practice_cursors"][0]["position"], 2);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.store.load().unwrap()).unwrap(),
|
||||
next
|
||||
);
|
||||
|
||||
random.debug_moves("repeat");
|
||||
assert_eq!(serde_json::to_value(random.session.stats()).unwrap(), next);
|
||||
assert_board_matches_session(&random);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_next_blocks_duplicate_work_and_applies_delivery_exactly_once() {
|
||||
let fixture = training(
|
||||
"1. e4 e5 (1... c5) 2. Nf3 (2. c4) *",
|
||||
TrainingMode::Both,
|
||||
"async-next-delivery",
|
||||
);
|
||||
let mut random = TrainingUi::new_random(
|
||||
&fixture.repertoire,
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
fixture.store.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
random.debug_moves("");
|
||||
let old_path = random.session.path().to_vec();
|
||||
let old_scope = random.session.scope().clone();
|
||||
let old_positions = random.positions.clone();
|
||||
let old_stats = serde_json::to_vec(random.session.stats()).unwrap();
|
||||
let generation = random.next_generation;
|
||||
|
||||
random.next_path();
|
||||
assert!(random.next_job.is_some());
|
||||
assert_eq!(random.next_generation, generation.wrapping_add(1));
|
||||
assert_eq!(random.session.path(), old_path);
|
||||
assert_eq!(random.positions, old_positions);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(random.session.stats()).unwrap(),
|
||||
old_stats
|
||||
);
|
||||
random.next_path();
|
||||
assert_eq!(random.next_generation, generation.wrapping_add(1));
|
||||
random.restart();
|
||||
assert_eq!(random.session.scope(), &old_scope);
|
||||
assert_eq!(random.session.path(), old_path);
|
||||
|
||||
random.deliver_next();
|
||||
assert!(random.next_job.is_none());
|
||||
assert!(random.session.attempts().is_empty());
|
||||
assert_board_matches_session(&random);
|
||||
let delivered_stats = serde_json::to_value(random.session.stats()).unwrap();
|
||||
assert_eq!(delivered_stats["random_practice_cursors"][0]["position"], 2);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.store.load().unwrap()).unwrap(),
|
||||
delivered_stats
|
||||
);
|
||||
let delivered_path = random.session.path().to_vec();
|
||||
random.poll_next();
|
||||
assert_eq!(random.session.path(), delivered_path);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.session.stats()).unwrap(),
|
||||
delivered_stats
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_next_computation_error_preserves_the_current_session() {
|
||||
let mut training = training_queue(
|
||||
"1. e4 e5 *",
|
||||
TrainingMode::Both,
|
||||
"async-next-error",
|
||||
QueueMode::Practice,
|
||||
TrainingScope::from_prefix(vec!["e2e4".into()]),
|
||||
);
|
||||
training.debug_moves("");
|
||||
let old_path = training.session.path().to_vec();
|
||||
let old_scope = training.session.scope().clone();
|
||||
let old_positions = training.positions.clone();
|
||||
let old_stats = serde_json::to_vec(training.session.stats()).unwrap();
|
||||
training.repertoire.pgn = parse_str("1. d4 d5 *").game.to_pgn();
|
||||
|
||||
training.next_path();
|
||||
training.deliver_next();
|
||||
assert!(training.next_job.is_none());
|
||||
assert!(
|
||||
training
|
||||
.message
|
||||
.as_ref()
|
||||
.is_some_and(|message| message.contains("invalid training scope"))
|
||||
);
|
||||
assert_eq!(training.session.path(), old_path);
|
||||
assert_eq!(training.session.scope(), &old_scope);
|
||||
assert_eq!(training.positions, old_positions);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(training.session.stats()).unwrap(),
|
||||
old_stats
|
||||
);
|
||||
assert_board_matches_session(&training);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_next_save_error_remains_visible_after_successful_computation() {
|
||||
let fixture = training(
|
||||
"1. e4 e5 (1... c5) 2. Nf3 *",
|
||||
TrainingMode::Both,
|
||||
"async-next-save-error",
|
||||
);
|
||||
let mut random = TrainingUi::new_random(
|
||||
&fixture.repertoire,
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
fixture.store.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let mut external = random.store.load().unwrap();
|
||||
random.store.save(&mut external).unwrap();
|
||||
|
||||
random.next_path();
|
||||
random.deliver_next();
|
||||
assert!(random.next_job.is_none());
|
||||
assert!(random.save_error.is_some());
|
||||
assert!(random.has_unsaved());
|
||||
assert_eq!(random.session.stats().revision, 1);
|
||||
assert_board_matches_session(&random);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_mainline_scope_end_is_accepted() {
|
||||
let game =
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
|
|
@ -10,8 +10,8 @@ use chess_core::shakmaty::Color;
|
|||
use chess_core::{Game, NodeId, PgnDatabase, Severity};
|
||||
use egui::{Key, Modifiers, RichText, Ui};
|
||||
use trainer::repertoire::{
|
||||
Library, LibraryStore, MergeReport, MoveKey, QueueMode, Repertoire, RepertoireId,
|
||||
RepertoireTree, SrsPolicy, StatsData, StatsStore, TrainingMode, TrainingScope, fen4,
|
||||
Library, LibraryStore, MergeReport, QueueMode, Repertoire, RepertoireId, RepertoireTree,
|
||||
SrsPolicy, StatsData, StatsStore, TrainingMode, TrainingScope, fen4,
|
||||
};
|
||||
|
||||
use crate::board::{BoardState, BoardView};
|
||||
|
|
@ -46,6 +46,11 @@ struct ImportPreview {
|
|||
target: Option<RepertoireId>,
|
||||
}
|
||||
|
||||
struct LibraryLoadError {
|
||||
library: Option<Library>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct CountKey {
|
||||
id: RepertoireId,
|
||||
|
|
@ -83,8 +88,6 @@ pub struct RepertoireUi {
|
|||
error: Option<String>,
|
||||
selected: Option<RepertoireId>,
|
||||
detail: bool,
|
||||
active: NodeId,
|
||||
scope: TrainingScope,
|
||||
tree: Option<Arc<RepertoireTree>>,
|
||||
trees: HashMap<RepertoireId, Arc<RepertoireTree>>,
|
||||
counts: HashMap<CountKey, Option<usize>>,
|
||||
|
|
@ -92,13 +95,9 @@ pub struct RepertoireUi {
|
|||
indexing: bool,
|
||||
preparing: bool,
|
||||
training_generation: u64,
|
||||
rows: Vec<(NodeId, usize)>,
|
||||
expanded: HashSet<NodeId>,
|
||||
cleanup: Option<RepertoireId>,
|
||||
board: BoardState,
|
||||
mode: TrainingMode,
|
||||
queue: QueueMode,
|
||||
policy: SrsPolicy,
|
||||
training: Option<TrainingUi>,
|
||||
training_visible: bool,
|
||||
return_to_game: Option<String>,
|
||||
|
|
@ -121,9 +120,9 @@ impl RepertoireUi {
|
|||
Self::with_stores(library_store, stats_store)
|
||||
}
|
||||
fn with_stores(library_store: LibraryStore, stats_store: StatsStore) -> Self {
|
||||
let (library, library_error) = match library_store.load() {
|
||||
let (library, library_error) = match load_library(&library_store) {
|
||||
Ok(data) => (data, None),
|
||||
Err(e) => (Library::default(), Some(e.to_string())),
|
||||
Err(e) => (e.library.unwrap_or_default(), Some(e.message)),
|
||||
};
|
||||
let (stats, stats_error) = match stats_store.load() {
|
||||
Ok(data) => (data, None),
|
||||
|
|
@ -141,8 +140,6 @@ impl RepertoireUi {
|
|||
error: None,
|
||||
selected,
|
||||
detail: false,
|
||||
active: NodeId::ROOT,
|
||||
scope: TrainingScope::whole(),
|
||||
tree: None,
|
||||
trees: HashMap::new(),
|
||||
counts: HashMap::new(),
|
||||
|
|
@ -150,13 +147,9 @@ impl RepertoireUi {
|
|||
indexing: false,
|
||||
preparing: false,
|
||||
training_generation: 0,
|
||||
rows: Vec::new(),
|
||||
expanded: HashSet::new(),
|
||||
cleanup: None,
|
||||
board: BoardState::default(),
|
||||
mode: TrainingMode::White,
|
||||
queue: QueueMode::Practice,
|
||||
policy: SrsPolicy::Due,
|
||||
training: None,
|
||||
training_visible: false,
|
||||
return_to_game: None,
|
||||
|
|
@ -217,16 +210,11 @@ impl RepertoireUi {
|
|||
self.preparing = false;
|
||||
self.selected = Some(id.clone());
|
||||
self.detail = true;
|
||||
self.active = NodeId::ROOT;
|
||||
self.expanded.clear();
|
||||
self.scope = TrainingScope::whole();
|
||||
let (mode, queue) = settings
|
||||
self.mode = settings
|
||||
.repertoire_modes
|
||||
.get(id.as_str())
|
||||
.copied()
|
||||
.unwrap_or((TrainingMode::White, QueueMode::Practice));
|
||||
self.mode = mode;
|
||||
self.queue = queue;
|
||||
.map(|(mode, _)| *mode)
|
||||
.unwrap_or(TrainingMode::White);
|
||||
self.update_selected_tree();
|
||||
}
|
||||
fn update_selected_tree(&mut self) {
|
||||
|
|
@ -235,13 +223,9 @@ impl RepertoireUi {
|
|||
.as_ref()
|
||||
.and_then(|id| self.trees.get(id))
|
||||
.cloned();
|
||||
self.rows = self
|
||||
.tree
|
||||
.as_ref()
|
||||
.map(|tree| tree_rows(tree.game(), &self.expanded))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
fn rebuild_tree(&mut self) {
|
||||
normalize_library(&mut self.library);
|
||||
self.counts.clear();
|
||||
self.index_generation += 1;
|
||||
self.indexing = true;
|
||||
|
|
@ -266,6 +250,7 @@ impl RepertoireUi {
|
|||
if self.library_error.is_some() {
|
||||
return false;
|
||||
}
|
||||
normalize_library(&mut library);
|
||||
match self.library_store.save(&mut library) {
|
||||
Ok(()) => {
|
||||
self.library = library;
|
||||
|
|
@ -312,19 +297,11 @@ impl RepertoireUi {
|
|||
else {
|
||||
return;
|
||||
};
|
||||
let queue = if self.mode == TrainingMode::Both && self.queue == QueueMode::SpacedRepetition
|
||||
{
|
||||
QueueMode::LeastRecent
|
||||
} else {
|
||||
self.queue
|
||||
};
|
||||
if self.preparing {
|
||||
return;
|
||||
}
|
||||
let repertoire = r.clone();
|
||||
let scope = self.scope.clone();
|
||||
let mode = self.mode;
|
||||
let policy = self.policy;
|
||||
let stats = self.stats.clone();
|
||||
let store = self.stats_store.clone();
|
||||
let tx = self.tx.clone();
|
||||
|
|
@ -332,21 +309,12 @@ impl RepertoireUi {
|
|||
let generation = self.training_generation;
|
||||
settings
|
||||
.repertoire_modes
|
||||
.insert(r.id.to_string(), (mode, queue));
|
||||
.insert(r.id.to_string(), (mode, QueueMode::Practice));
|
||||
self.preparing = true;
|
||||
if let Err(error) = crate::platform::spawn("repertoire-training-start", move || {
|
||||
let result = TrainingUi::new_with_policy(
|
||||
&repertoire,
|
||||
scope,
|
||||
mode,
|
||||
queue,
|
||||
stats,
|
||||
store,
|
||||
false,
|
||||
policy,
|
||||
)
|
||||
.map(Box::new)
|
||||
.map_err(|e| e.to_string());
|
||||
let result = TrainingUi::new_random(&repertoire, mode, stats, store, false)
|
||||
.map(Box::new)
|
||||
.map_err(|e| e.to_string());
|
||||
let _ = tx.send(Event::TrainingReady(generation, result));
|
||||
}) {
|
||||
self.preparing = false;
|
||||
|
|
@ -490,10 +458,7 @@ impl RepertoireUi {
|
|||
self.debug_moves(&moves);
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
self.error =
|
||||
Some(tr("No enabled moves for this mode and depth").to_owned())
|
||||
}
|
||||
Ok(_) => self.error = Some(tr("No targets in this mode").to_owned()),
|
||||
Err(error) => self.error = Some(error),
|
||||
}
|
||||
}
|
||||
|
|
@ -637,13 +602,19 @@ impl RepertoireUi {
|
|||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(e).color(ui.visuals().error_fg_color));
|
||||
if ui.button(tr("Retry")).clicked() {
|
||||
match self.library_store.load() {
|
||||
match load_library(&self.library_store) {
|
||||
Ok(data) => {
|
||||
self.library = data;
|
||||
self.library_error = None;
|
||||
self.rebuild_tree();
|
||||
}
|
||||
Err(e) => self.library_error = Some(e.to_string()),
|
||||
Err(e) => {
|
||||
if let Some(library) = e.library {
|
||||
self.library = library;
|
||||
self.rebuild_tree();
|
||||
}
|
||||
self.library_error = Some(e.message);
|
||||
}
|
||||
}
|
||||
match self.stats_store.load() {
|
||||
Ok(data) => {
|
||||
|
|
@ -778,21 +749,23 @@ impl RepertoireUi {
|
|||
} else {
|
||||
110.0
|
||||
}))
|
||||
.column(egui_extras::Column::exact(if compact {
|
||||
82.0
|
||||
} else {
|
||||
110.0
|
||||
}))
|
||||
.column(egui_extras::Column::exact(if compact {
|
||||
82.0
|
||||
} else {
|
||||
130.0
|
||||
}))
|
||||
.column(egui_extras::Column::exact(28.0))
|
||||
.header(30.0, |mut header| {
|
||||
for key in ["Name", "White: due", "Black: due", "Both sides", ""] {
|
||||
for (column, key) in ["Name", "Variants", ""].into_iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate());
|
||||
if column == 1 {
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(key)).strong())
|
||||
.truncate(),
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate());
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
|
|
@ -814,33 +787,15 @@ impl RepertoireUi {
|
|||
open = Some(r.id.clone());
|
||||
}
|
||||
});
|
||||
for mode in [TrainingMode::White, TrainingMode::Black] {
|
||||
row.col(|ui| {
|
||||
match self.task_count(
|
||||
&r.id,
|
||||
mode,
|
||||
QueueMode::SpacedRepetition,
|
||||
SrsPolicy::Due,
|
||||
&TrainingScope::whole(),
|
||||
) {
|
||||
Some(n) => {
|
||||
ui.label(n.to_string());
|
||||
}
|
||||
None => {
|
||||
ui.spinner();
|
||||
ui.ctx().request_repaint_after(
|
||||
std::time::Duration::from_millis(100),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
row.col(|ui| {
|
||||
ui.label(
|
||||
self.stats
|
||||
.runs(&r.id, TrainingMode::Both)
|
||||
.map_or_else(|| "—".to_owned(), |s| s.completions.to_string()),
|
||||
let count = self.task_count(
|
||||
&r.id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&TrainingScope::whole(),
|
||||
);
|
||||
count_cell(ui, count);
|
||||
});
|
||||
row.col(|ui| {
|
||||
ui.menu_button("⋯", |ui| {
|
||||
|
|
@ -991,7 +946,7 @@ impl RepertoireUi {
|
|||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.add_enabled_ui(!self.preparing, |ui| {
|
||||
let previous = (self.mode, self.queue);
|
||||
let previous_mode = self.mode;
|
||||
ui.add(egui::Label::new(RichText::new(&r.name).heading()).truncate())
|
||||
.on_hover_text(&r.name);
|
||||
ui.add_space(6.0);
|
||||
|
|
@ -1004,101 +959,13 @@ impl RepertoireUi {
|
|||
}
|
||||
});
|
||||
ui.separator();
|
||||
egui::Grid::new("repertoire_options")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 8.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(tr("Depth"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let mut depth = r.max_plies;
|
||||
let mut unlimited = depth == u32::MAX;
|
||||
let mut changed =
|
||||
ui.checkbox(&mut unlimited, tr("No limit")).changed();
|
||||
if !unlimited {
|
||||
if depth == u32::MAX {
|
||||
depth = 20;
|
||||
}
|
||||
changed |= ui
|
||||
.add(
|
||||
egui::DragValue::new(&mut depth)
|
||||
.range(1..=10000)
|
||||
.suffix(format!(" {}", tr("half-moves"))),
|
||||
)
|
||||
.changed();
|
||||
}
|
||||
if changed {
|
||||
let mut library = self.library.clone();
|
||||
if let Some(r) = library.repertoire_mut(id) {
|
||||
r.max_plies = if unlimited { u32::MAX } else { depth };
|
||||
}
|
||||
self.persist(library);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Color"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for mode in
|
||||
[TrainingMode::White, TrainingMode::Black, TrainingMode::Both]
|
||||
{
|
||||
ui.selectable_value(&mut self.mode, mode, mode_label(mode));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Mode"));
|
||||
egui::ComboBox::from_id_salt("repertoire_queue")
|
||||
.width(180.0)
|
||||
.wrap_mode(egui::TextWrapMode::Truncate)
|
||||
.selected_text(queue_label(self.queue))
|
||||
.show_ui(ui, |ui| {
|
||||
for queue in [
|
||||
QueueMode::Practice,
|
||||
QueueMode::SpacedRepetition,
|
||||
] {
|
||||
if self.mode != TrainingMode::Both
|
||||
|| queue != QueueMode::SpacedRepetition
|
||||
{
|
||||
ui.selectable_value(
|
||||
&mut self.queue,
|
||||
queue,
|
||||
queue_label(queue),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
if self.mode == TrainingMode::Both
|
||||
&& self.queue != QueueMode::Practice
|
||||
{
|
||||
self.queue = QueueMode::Practice;
|
||||
}
|
||||
ui.end_row();
|
||||
if self.mode != TrainingMode::Both
|
||||
&& self.queue == QueueMode::SpacedRepetition
|
||||
{
|
||||
ui.label(tr("Spaced schedule"));
|
||||
egui::ComboBox::from_id_salt("srs_policy")
|
||||
.selected_text(policy_label(self.policy))
|
||||
.show_ui(ui, |ui| {
|
||||
for policy in [
|
||||
SrsPolicy::Due,
|
||||
SrsPolicy::Introduce,
|
||||
SrsPolicy::EarlyReview,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut self.policy,
|
||||
policy,
|
||||
policy_label(policy),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Color"));
|
||||
for mode in [TrainingMode::White, TrainingMode::Black, TrainingMode::Both] {
|
||||
ui.selectable_value(&mut self.mode, mode, mode_label(mode));
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(tr(if self.queue == QueueMode::Practice {
|
||||
"Play a variation from start to finish. Any enabled move is accepted; the program plays the other side."
|
||||
} else {
|
||||
"Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded."
|
||||
}));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let available = self.available_tasks();
|
||||
if available.is_none() {
|
||||
|
|
@ -1108,17 +975,9 @@ impl RepertoireUi {
|
|||
}
|
||||
let count_label =
|
||||
available.map_or_else(|| "…".to_owned(), |n| n.to_string());
|
||||
ui.label(format!(
|
||||
"{}: {count_label}",
|
||||
if self.mode == TrainingMode::Both || self.queue == QueueMode::Practice {
|
||||
tr("Paths")
|
||||
} else {
|
||||
tr("Moves")
|
||||
}
|
||||
));
|
||||
ui.label(format!("{}: {count_label}", tr("Paths")));
|
||||
let ready = !self.preparing
|
||||
&& (available.is_some_and(|n| n > 0)
|
||||
|| ((self.mode == TrainingMode::Both || self.queue == QueueMode::Practice) && self.tree.is_some()))
|
||||
&& available.is_some_and(|n| n > 0)
|
||||
&& self.stats_error.is_none()
|
||||
&& self.library_error.is_none();
|
||||
if ui
|
||||
|
|
@ -1128,56 +987,30 @@ impl RepertoireUi {
|
|||
self.start(settings);
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
if self.mode != TrainingMode::Both
|
||||
&& self.queue == QueueMode::SpacedRepetition
|
||||
&& self.policy == SrsPolicy::Due
|
||||
&& available == Some(0)
|
||||
&& ui.button(tr("Introduce new moves")).clicked()
|
||||
{
|
||||
self.policy = SrsPolicy::Introduce;
|
||||
}
|
||||
});
|
||||
if matches!(self.queue, QueueMode::ReviewInOrder | QueueMode::LeastRecent) {
|
||||
ui.label(tr("Early review · schedule unchanged"));
|
||||
}
|
||||
if previous != (self.mode, self.queue) {
|
||||
if previous_mode != self.mode {
|
||||
settings
|
||||
.repertoire_modes
|
||||
.insert(id.to_string(), (self.mode, self.queue));
|
||||
.insert(id.to_string(), (self.mode, QueueMode::Practice));
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(if self.scope.prefix.is_empty() {
|
||||
tr("Whole repertoire").to_owned()
|
||||
} else {
|
||||
format!("{}: {}", tr("Scope"), self.scope.prefix.join(" "))
|
||||
});
|
||||
if ui.button(tr("Reset scope")).clicked() {
|
||||
self.scope = TrainingScope::whole();
|
||||
}
|
||||
if self.active != NodeId::ROOT
|
||||
&& ui.button(tr("Use selected as scope")).clicked()
|
||||
&& let Some(path) = self.tree.as_ref().and_then(|t| t.path(self.active))
|
||||
{
|
||||
self.scope = TrainingScope::from_prefix(path.to_vec());
|
||||
}
|
||||
if ui.button(tr("End scope here")).clicked()
|
||||
&& let Some(path) = self.tree.as_ref().and_then(|t| t.path(self.active))
|
||||
{
|
||||
self.scope.end_prefix = Some(path.to_vec());
|
||||
}
|
||||
});
|
||||
if self.import.is_some() {
|
||||
self.import_preview(ui, settings);
|
||||
}
|
||||
ui.separator();
|
||||
self.tree_panel(ui, r);
|
||||
self.statistics_panel(ui, r);
|
||||
});
|
||||
});
|
||||
}
|
||||
fn available_tasks(&mut self) -> Option<usize> {
|
||||
let id = self.selected.clone()?;
|
||||
self.task_count(&id, self.mode, self.queue, self.policy, &self.scope.clone())
|
||||
self.task_count(
|
||||
&id,
|
||||
self.mode,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&TrainingScope::whole(),
|
||||
)
|
||||
}
|
||||
fn task_count(
|
||||
&mut self,
|
||||
|
|
@ -1223,7 +1056,19 @@ impl RepertoireUi {
|
|||
});
|
||||
self.counts.insert(key.clone(), None);
|
||||
if let Err(error) = crate::platform::spawn("repertoire-count", move || {
|
||||
let count = if mode == TrainingMode::Both || queue == QueueMode::Practice {
|
||||
let count = if queue == QueueMode::Practice {
|
||||
use chess_core::shakmaty::Position;
|
||||
let start_turn = tree.position(tree.root()).map(|position| position.turn());
|
||||
let mut count = 0usize;
|
||||
tree.visit_training_paths(&job_key.scope, |moves| {
|
||||
if start_turn.is_some_and(|turn| path_has_mode_move(mode, turn, moves.len())) {
|
||||
count = count.saturating_add(1);
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
})
|
||||
.map(|()| count)
|
||||
.unwrap_or(0)
|
||||
} else if mode == TrainingMode::Both {
|
||||
tree.training_path_count(&job_key.scope).unwrap_or(0)
|
||||
} else if queue == QueueMode::SpacedRepetition {
|
||||
stats
|
||||
|
|
@ -1245,7 +1090,7 @@ impl RepertoireUi {
|
|||
let Some(tree) = &self.tree else {
|
||||
return;
|
||||
};
|
||||
let Some(pos) = tree.game().position(self.active) else {
|
||||
let Some(pos) = tree.game().position(NodeId::ROOT) else {
|
||||
return;
|
||||
};
|
||||
let side = ui.available_width().min(ui.available_height()).max(80.0);
|
||||
|
|
@ -1279,103 +1124,10 @@ impl RepertoireUi {
|
|||
.show(ui, &mut self.board);
|
||||
});
|
||||
}
|
||||
fn tree_panel(&mut self, ui: &mut Ui, r: &Repertoire) {
|
||||
let Some(tree) = &self.tree else {
|
||||
fn statistics_panel(&mut self, ui: &mut Ui, r: &Repertoire) {
|
||||
if self.tree.is_none() {
|
||||
return;
|
||||
};
|
||||
let game = tree.game();
|
||||
let mut select = None;
|
||||
let mut toggle = None;
|
||||
let mut expand = None;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(tr("Tree"));
|
||||
if ui
|
||||
.selectable_label(self.active == NodeId::ROOT, tr("Start position"))
|
||||
.clicked()
|
||||
{
|
||||
select = Some(NodeId::ROOT);
|
||||
}
|
||||
});
|
||||
let rows = &self.rows;
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_moves")
|
||||
.max_height(260.0)
|
||||
.show_rows(ui, 24.0, rows.len(), |ui, range| {
|
||||
for index in range {
|
||||
let (node, depth) = rows[index];
|
||||
let path = tree.path(node).unwrap_or(&[]);
|
||||
let disabled = r.is_prefix_disabled(path);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space((depth.min(10) as f32) * 12.0);
|
||||
let mut enabled = !disabled;
|
||||
if ui
|
||||
.checkbox(&mut enabled, "")
|
||||
.on_hover_text(tr("Enable for training"))
|
||||
.changed()
|
||||
{
|
||||
toggle = Some((path.to_vec(), !enabled));
|
||||
}
|
||||
if game.children(node).len() > 1 {
|
||||
let is_open = self.expanded.contains(&node);
|
||||
if ui
|
||||
.add_sized(
|
||||
[18.0, 20.0],
|
||||
egui::Button::new(if is_open { "▾" } else { "▸" }).frame(false),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
expand = Some(node);
|
||||
}
|
||||
} else {
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
let label = game.move_label(node).unwrap_or_default();
|
||||
let text = if disabled {
|
||||
RichText::new(crate::san::show(&label)).weak()
|
||||
} else {
|
||||
RichText::new(crate::san::show(&label))
|
||||
};
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(100.0, 22.0),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
if ui.selectable_label(self.active == node, text).clicked() {
|
||||
select = Some(node);
|
||||
}
|
||||
},
|
||||
);
|
||||
if disabled {
|
||||
ui.label(RichText::new(tr(" ∅ not trained")).weak());
|
||||
}
|
||||
if path.len() > r.max_plies as usize {
|
||||
ui.label(RichText::new(format!(">{}", r.max_plies)).weak());
|
||||
}
|
||||
if !self.scope.prefix.is_empty() && path == self.scope.prefix {
|
||||
ui.label("▶");
|
||||
}
|
||||
let transpositions = tree.transpositions(node);
|
||||
if transpositions.len() > 1 {
|
||||
ui.menu_button(format!("⇄ {}", transpositions.len()), |ui| {
|
||||
for alternate in transpositions {
|
||||
if ui.button(prefix_label(game, *alternate)).clicked() {
|
||||
select = Some(*alternate);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(n) = game.node(node) {
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
RichText::new(n.comments_after().join(" ")).weak(),
|
||||
)
|
||||
.truncate(),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_statistics")
|
||||
.show(ui, |ui| {
|
||||
|
|
@ -1401,110 +1153,7 @@ impl RepertoireUi {
|
|||
format_time(run.last)
|
||||
));
|
||||
}
|
||||
if let Some(n) = game.node(self.active) {
|
||||
ui.label(
|
||||
n.comments_before()
|
||||
.iter()
|
||||
.chain(n.comments_after())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
ui.label(
|
||||
n.nags()
|
||||
.iter()
|
||||
.map(|n| format!("${}", n.0))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
);
|
||||
}
|
||||
if self.active != NodeId::ROOT
|
||||
&& let Some(before) = game.position_before(self.active)
|
||||
{
|
||||
let uci = tree
|
||||
.path(self.active)
|
||||
.and_then(|p| p.last())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let key = MoveKey {
|
||||
repertoire_id: r.id.clone(),
|
||||
mode: self.mode,
|
||||
position_fen4: fen4(before),
|
||||
expected_uci: if self.mode == TrainingMode::Both {
|
||||
String::new()
|
||||
} else {
|
||||
uci
|
||||
},
|
||||
};
|
||||
ui.strong(tr("Move statistics"));
|
||||
if let Some(stats) = self.stats.get(&key) {
|
||||
ui.label(format!(
|
||||
"{}: {} · {}: {} · {}: {}",
|
||||
tr("Correct"),
|
||||
stats.correct,
|
||||
tr("Wrong"),
|
||||
stats.wrong,
|
||||
tr("Hints"),
|
||||
stats.hints
|
||||
));
|
||||
ui.label(format!(
|
||||
"{}: {}",
|
||||
tr("Last attempt"),
|
||||
format_time(stats.last_attempt)
|
||||
));
|
||||
if self.mode != TrainingMode::Both {
|
||||
ui.label(format!("{}: {}", tr("Next review"), format_time(stats.due)));
|
||||
}
|
||||
} else {
|
||||
ui.label(tr("No attempts in the selected mode"));
|
||||
}
|
||||
}
|
||||
if self.mode == TrainingMode::Both {
|
||||
let prefix = tree.path(self.active).unwrap_or(&[]);
|
||||
ui.strong(tr("Branch statistics"));
|
||||
for path in
|
||||
self.stats.path_stats.iter().filter(|p| {
|
||||
p.key.repertoire_id == r.id && p.key.path.starts_with(prefix)
|
||||
})
|
||||
{
|
||||
ui.label(format!(
|
||||
"{} · {}: {} · {}",
|
||||
path.key.path.join(" "),
|
||||
tr("Completions"),
|
||||
path.completions,
|
||||
format_time(path.last_completion)
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(node) = select {
|
||||
self.active = node;
|
||||
for parent in game.path(node) {
|
||||
self.expanded.insert(parent);
|
||||
}
|
||||
}
|
||||
if let Some(node) = expand
|
||||
&& !self.expanded.remove(&node)
|
||||
{
|
||||
self.expanded.insert(node);
|
||||
}
|
||||
if select.is_some() || expand.is_some() {
|
||||
self.rows = tree_rows(game, &self.expanded);
|
||||
}
|
||||
if let Some((path, disabled)) = toggle {
|
||||
let mut library = self.library.clone();
|
||||
if let Some(rep) = library.repertoire_mut(&r.id) {
|
||||
if !disabled && !rep.disabled_prefixes.contains(&path) {
|
||||
self.error = Some(tr("Enable the parent branch first").to_owned());
|
||||
return;
|
||||
}
|
||||
if let Err(e) = rep.set_prefix_disabled(&path, disabled) {
|
||||
self.error = Some(e.to_string());
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.persist(library);
|
||||
}
|
||||
}
|
||||
fn show_add(&mut self, ui: &mut Ui, actions: &mut Vec<RepertoireAction>) {
|
||||
let Some(mut add) = self.add.take() else {
|
||||
|
|
@ -1634,7 +1283,6 @@ impl RepertoireUi {
|
|||
"black" => TrainingMode::Black,
|
||||
_ => TrainingMode::Both,
|
||||
};
|
||||
self.queue = QueueMode::Practice;
|
||||
self.start(settings);
|
||||
}
|
||||
_ => {}
|
||||
|
|
@ -1731,43 +1379,56 @@ fn read_import(
|
|||
target,
|
||||
})
|
||||
}
|
||||
fn tree_rows(game: &Game, expanded: &HashSet<NodeId>) -> Vec<(NodeId, usize)> {
|
||||
let mut rows = Vec::new();
|
||||
let mut stack: Vec<_> = game
|
||||
.children(NodeId::ROOT)
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|id| (*id, 0))
|
||||
.collect();
|
||||
while let Some((id, depth)) = stack.pop() {
|
||||
rows.push((id, depth));
|
||||
for (index, child) in game.children(id).iter().enumerate().rev() {
|
||||
if index == 0 || expanded.contains(&id) {
|
||||
stack.push((*child, depth + usize::from(index != 0)));
|
||||
}
|
||||
}
|
||||
fn path_has_mode_move(mode: TrainingMode, start_turn: Color, plies: usize) -> bool {
|
||||
match mode.user_color() {
|
||||
Some(color) => plies > usize::from(start_turn != color),
|
||||
None => plies > 0,
|
||||
}
|
||||
rows
|
||||
}
|
||||
fn count_cell(ui: &mut Ui, count: Option<usize>) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if let Some(count) = count {
|
||||
ui.label(count.to_string());
|
||||
} else {
|
||||
ui.spinner();
|
||||
ui.ctx()
|
||||
.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
});
|
||||
}
|
||||
fn now() -> i64 {
|
||||
web_time::SystemTime::now()
|
||||
.duration_since(web_time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as i64)
|
||||
}
|
||||
fn queue_label(q: QueueMode) -> &'static str {
|
||||
tr(match q {
|
||||
QueueMode::Practice => "Play through variations",
|
||||
QueueMode::SpacedRepetition => "Review individual moves",
|
||||
QueueMode::ReviewInOrder => "Review in order",
|
||||
QueueMode::LeastRecent => "Least recent and unseen first",
|
||||
})
|
||||
fn load_library(store: &LibraryStore) -> Result<Library, LibraryLoadError> {
|
||||
let mut library = store.load().map_err(|error| LibraryLoadError {
|
||||
library: None,
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
if normalize_library(&mut library)
|
||||
&& let Err(error) = store.save(&mut library)
|
||||
{
|
||||
return Err(LibraryLoadError {
|
||||
library: Some(library),
|
||||
message: error.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(library)
|
||||
}
|
||||
fn policy_label(p: SrsPolicy) -> &'static str {
|
||||
tr(match p {
|
||||
SrsPolicy::Due => "Review due moves",
|
||||
SrsPolicy::Introduce => "Introduce new moves",
|
||||
SrsPolicy::EarlyReview => "Review future moves early",
|
||||
})
|
||||
fn normalize_library(library: &mut Library) -> bool {
|
||||
let mut changed = false;
|
||||
for repertoire in &mut library.repertoires {
|
||||
if repertoire.max_plies != u32::MAX {
|
||||
repertoire.max_plies = u32::MAX;
|
||||
changed = true;
|
||||
}
|
||||
if !repertoire.disabled_prefixes.is_empty() {
|
||||
repertoire.disabled_prefixes.clear();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
fn prefix_label(game: &Game, at: NodeId) -> String {
|
||||
game.path(at)
|
||||
|
|
|
|||
|
|
@ -50,8 +50,7 @@ impl Fixture {
|
|||
}
|
||||
|
||||
fn start(&mut self) {
|
||||
self.ui.mode = TrainingMode::Both;
|
||||
self.ui.queue = QueueMode::ReviewInOrder;
|
||||
self.ui.mode = TrainingMode::White;
|
||||
self.ui.start(&mut self.settings);
|
||||
assert!(self.ui.preparing);
|
||||
}
|
||||
|
|
@ -63,6 +62,127 @@ impl Drop for Fixture {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_persists_migration_of_legacy_training_limits() {
|
||||
let f = Fixture::new();
|
||||
let store = LibraryStore::new(f.dir.join("legacy-limits.json"));
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create("Legacy limits", &chess_core::parse_str("1. e4 e5 *").game)
|
||||
.unwrap();
|
||||
let repertoire = library.repertoire_mut(&id).unwrap();
|
||||
repertoire.max_plies = 1;
|
||||
repertoire
|
||||
.set_prefix_disabled(&["e2e4".to_owned()], true)
|
||||
.unwrap();
|
||||
let pgn = repertoire.pgn.clone();
|
||||
store.save(&mut library).unwrap();
|
||||
|
||||
let ui = RepertoireUi::with_stores(
|
||||
store.clone(),
|
||||
StatsStore::new(f.dir.join("legacy-stats.json")),
|
||||
);
|
||||
assert!(ui.library_error.is_none(), "{:?}", ui.library_error);
|
||||
let saved = store.load().unwrap();
|
||||
for library in [&ui.library, &saved] {
|
||||
let repertoire = library.repertoire(&id).unwrap();
|
||||
assert_eq!(repertoire.max_plies, u32::MAX);
|
||||
assert!(repertoire.disabled_prefixes.is_empty());
|
||||
assert_eq!(repertoire.pgn, pgn);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_write_failure_keeps_the_loaded_library_available() {
|
||||
let f = Fixture::new();
|
||||
let store = LibraryStore::new(f.dir.join("migration-failure.json"));
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create(
|
||||
"Read only migration",
|
||||
&chess_core::parse_str("1. e4 e5 *").game,
|
||||
)
|
||||
.unwrap();
|
||||
let repertoire = library.repertoire_mut(&id).unwrap();
|
||||
repertoire.max_plies = 1;
|
||||
repertoire
|
||||
.set_prefix_disabled(&["e2e4".to_owned()], true)
|
||||
.unwrap();
|
||||
store.save(&mut library).unwrap();
|
||||
let lock = f.dir.join("migration-failure.json.lock");
|
||||
std::fs::remove_file(&lock).unwrap();
|
||||
std::fs::create_dir(lock).unwrap();
|
||||
|
||||
let ui = RepertoireUi::with_stores(
|
||||
store.clone(),
|
||||
StatsStore::new(f.dir.join("migration-failure-stats.json")),
|
||||
);
|
||||
assert!(ui.library_error.is_some());
|
||||
let migrated = ui.library.repertoire(&id).unwrap();
|
||||
assert_eq!(migrated.max_plies, u32::MAX);
|
||||
assert!(migrated.disabled_prefixes.is_empty());
|
||||
let on_disk = store.load().unwrap();
|
||||
let unchanged = on_disk.repertoire(&id).unwrap();
|
||||
assert_eq!(unchanged.max_plies, 1);
|
||||
assert_eq!(unchanged.disabled_prefixes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn practice_count_requires_a_move_for_the_selected_color() {
|
||||
let mut f = Fixture::new();
|
||||
let mut library = f.ui.library.clone();
|
||||
let id = library
|
||||
.create("White only", &chess_core::parse_str("1. e4 *").game)
|
||||
.unwrap();
|
||||
assert!(f.ui.persist(library));
|
||||
f.deliver(f.completed_job());
|
||||
|
||||
for (mode, expected) in [
|
||||
(TrainingMode::White, 1),
|
||||
(TrainingMode::Black, 0),
|
||||
(TrainingMode::Both, 1),
|
||||
] {
|
||||
let scope = TrainingScope::whole();
|
||||
assert_eq!(
|
||||
f.ui.task_count(&id, mode, QueueMode::Practice, SrsPolicy::Due, &scope),
|
||||
None
|
||||
);
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.task_count(&id, mode, QueueMode::Practice, SrsPolicy::Due, &scope),
|
||||
Some(expected)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_normalizes_limits_before_saving_and_indexing() {
|
||||
let mut f = Fixture::new();
|
||||
let mut library = f.ui.library.clone();
|
||||
let repertoire = library.repertoire_mut(&f.id).unwrap();
|
||||
repertoire.max_plies = 1;
|
||||
repertoire
|
||||
.set_prefix_disabled(&["e2e4".to_owned()], true)
|
||||
.unwrap();
|
||||
let pgn = repertoire.pgn.clone();
|
||||
|
||||
assert!(f.ui.persist(library));
|
||||
let saved = f.ui.library_store.load().unwrap();
|
||||
for library in [&f.ui.library, &saved] {
|
||||
let repertoire = library.repertoire(&f.id).unwrap();
|
||||
assert_eq!(repertoire.max_plies, u32::MAX);
|
||||
assert!(repertoire.disabled_prefixes.is_empty());
|
||||
assert_eq!(repertoire.pgn, pgn);
|
||||
}
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.trees[&f.id]
|
||||
.training_path_count(&TrainingScope::whole())
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_index_cannot_replace_a_newer_rebuild() {
|
||||
let mut f = Fixture::new();
|
||||
|
|
@ -132,13 +252,47 @@ fn async_start_can_finish_a_real_opening_and_persist_its_statistics() {
|
|||
assert!(!training.has_unsaved());
|
||||
let saved = f.ui.stats_store.load().unwrap();
|
||||
assert_eq!(
|
||||
saved.runs(&f.id, TrainingMode::Both).unwrap().completions,
|
||||
saved.runs(&f.id, TrainingMode::White).unwrap().completions,
|
||||
1
|
||||
);
|
||||
assert_eq!(saved.move_stats.iter().map(|s| s.correct).sum::<u32>(), 2);
|
||||
assert_eq!(saved.move_stats.iter().map(|s| s.correct).sum::<u32>(), 1);
|
||||
assert!(f.ui.error.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_ignores_legacy_queue() {
|
||||
let mut f = Fixture::new();
|
||||
f.settings.repertoire_modes.insert(
|
||||
f.id.to_string(),
|
||||
(TrainingMode::White, QueueMode::SpacedRepetition),
|
||||
);
|
||||
f.ui.select(f.id.clone(), &f.settings);
|
||||
assert_eq!(f.ui.mode, TrainingMode::White);
|
||||
|
||||
f.ui.start(&mut f.settings);
|
||||
assert!(f.ui.preparing);
|
||||
assert_eq!(
|
||||
f.settings.repertoire_modes.get(f.id.as_str()),
|
||||
Some(&(TrainingMode::White, QueueMode::Practice))
|
||||
);
|
||||
|
||||
f.deliver(f.completed_job());
|
||||
assert!(f.ui.training_visible);
|
||||
f.ui.debug_moves("e2e4 e7e5");
|
||||
let training = f.ui.training.as_ref().unwrap();
|
||||
assert!(!training.target_available());
|
||||
assert!(!training.has_unsaved());
|
||||
assert_eq!(
|
||||
f.ui.stats_store
|
||||
.load()
|
||||
.unwrap()
|
||||
.runs(&f.id, TrainingMode::White)
|
||||
.unwrap()
|
||||
.completions,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_count_reuses_pending_work_across_minutes_and_discards_evicted_results() {
|
||||
let mut f = Fixture::new();
|
||||
|
|
@ -195,6 +349,70 @@ fn both_and_review_counts_have_no_minute_expiry_and_complete_asynchronously() {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variant_count_does_not_depend_on_completed_training_runs() {
|
||||
let mut f = Fixture::new();
|
||||
let game = chess_core::parse_str("1. e4 e5 (1... c5) 2. Nf3 *").game;
|
||||
let mut library = f.ui.library.clone();
|
||||
let id = library.create("Two paths", &game).unwrap();
|
||||
assert!(f.ui.persist(library));
|
||||
f.deliver(f.completed_job());
|
||||
assert!(f.ui.stats.runs(&id, TrainingMode::Both).is_none());
|
||||
|
||||
let scope = TrainingScope::whole();
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
None
|
||||
);
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
Some(2)
|
||||
);
|
||||
|
||||
f.ui.stats.runs.push(trainer::repertoire::RunStats {
|
||||
repertoire_id: id.clone(),
|
||||
mode: TrainingMode::Both,
|
||||
completions: 7,
|
||||
last: Some(now()),
|
||||
recent: Vec::new(),
|
||||
});
|
||||
f.ui.stats.revision += 1;
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
None
|
||||
);
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
Some(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual corpus import and indexing measurement"]
|
||||
fn corpus_import_preserves_source_and_reports_real_outcome() {
|
||||
|
|
@ -308,24 +526,3 @@ fn corpus_import_preserves_source_and_reports_real_outcome() {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expanding_and_collapsing_variations_only_changes_visible_rows() {
|
||||
let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Bc4 *").game;
|
||||
let before = game.canonical_tree();
|
||||
let e4 = game.children(NodeId::ROOT)[0];
|
||||
let e5 = game.children(e4)[0];
|
||||
let c5 = game.children(e4)[1];
|
||||
let bc4 = game.children(e5)[0];
|
||||
let nf3 = game.children(c5)[0];
|
||||
let mut expanded = HashSet::new();
|
||||
let collapsed = tree_rows(&game, &expanded);
|
||||
assert_eq!(collapsed, vec![(e4, 0), (e5, 0), (bc4, 0)]);
|
||||
expanded.insert(e4);
|
||||
let visible = tree_rows(&game, &expanded);
|
||||
assert_eq!(visible, vec![(e4, 0), (e5, 0), (bc4, 0), (c5, 1), (nf3, 1)]);
|
||||
assert_eq!(game.canonical_tree(), before);
|
||||
expanded.remove(&e4);
|
||||
assert_eq!(tree_rows(&game, &expanded), collapsed);
|
||||
assert_eq!(game.canonical_tree(), before);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,24 @@ fn strings(moves: &[&str]) -> Vec<String> {
|
|||
moves.iter().map(|mv| (*mv).to_owned()).collect()
|
||||
}
|
||||
|
||||
fn random_session(rep: &Repertoire, mode: TrainingMode, seed: u64) -> TrainingSession {
|
||||
TrainingSession::scoped_random_with_seed(
|
||||
rep,
|
||||
TrainingScope::whole(),
|
||||
mode,
|
||||
StatsData::default(),
|
||||
0,
|
||||
seed,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn random_route(session: &TrainingSession) -> Vec<String> {
|
||||
let mut route = session.scope().parent_prefix().to_vec();
|
||||
route.extend(session.suggested_path().unwrap().iter().cloned());
|
||||
route
|
||||
}
|
||||
|
||||
fn path_key(rep: &Repertoire, scope: &TrainingScope, path: &[String]) -> PathKey {
|
||||
PathKey {
|
||||
repertoire_id: rep.id.clone(),
|
||||
|
|
@ -1245,3 +1263,310 @@ fn practice_next_branch_hint_follows_proposal_and_both_path_completion_is_once()
|
|||
session.play_uci("d2d4", 12).unwrap();
|
||||
assert_eq!(session.hint(13).unwrap().uci, "d7d5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_practice_is_deterministic_and_covers_every_route_before_a_new_cycle() {
|
||||
let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *");
|
||||
let expected: std::collections::BTreeSet<Vec<String>> = RepertoireTree::new(&rep)
|
||||
.training_paths(&TrainingScope::whole())
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|path| path.moves)
|
||||
.collect();
|
||||
assert_eq!(expected.len(), 3);
|
||||
let mut left = random_session(&rep, TrainingMode::Both, 42);
|
||||
let mut right = random_session(&rep, TrainingMode::Both, 42);
|
||||
let mut routes = Vec::new();
|
||||
for step in 0..6 {
|
||||
assert_eq!(left.scope(), right.scope());
|
||||
assert_eq!(random_route(&left), random_route(&right));
|
||||
routes.push(random_route(&left));
|
||||
if step < 5 {
|
||||
left.next_path(step).unwrap();
|
||||
right.next_path(step).unwrap();
|
||||
}
|
||||
}
|
||||
for cycle in routes.chunks(3) {
|
||||
let actual: std::collections::BTreeSet<Vec<String>> = cycle.iter().cloned().collect();
|
||||
assert_eq!(actual.len(), 3);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_practice_mid_path_context_has_the_correct_side_for_every_mode() {
|
||||
let rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *");
|
||||
for mode in [TrainingMode::White, TrainingMode::Black, TrainingMode::Both] {
|
||||
let mut session = None;
|
||||
for seed in 0..64 {
|
||||
let candidate = random_session(&rep, mode, seed);
|
||||
if !candidate.path().is_empty() {
|
||||
session = Some(candidate);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut session = session.expect("a deterministic mid-path start");
|
||||
let start = session.path().len();
|
||||
assert!(start > 0);
|
||||
assert!(session.path().iter().all(|played| played.automatic));
|
||||
assert!(session.attempts().is_empty());
|
||||
assert_eq!(session.scope().prefix.len(), start + 1);
|
||||
assert_eq!(
|
||||
session.scope().prefix.last().unwrap(),
|
||||
&session.suggested_path().unwrap()[0]
|
||||
);
|
||||
assert_eq!(random_route(&session).len(), 6);
|
||||
assert_eq!(
|
||||
session.position_key(),
|
||||
session.path().last().unwrap().position_after
|
||||
);
|
||||
if let Some(color) = mode.user_color() {
|
||||
assert_eq!(session.position().turn(), color);
|
||||
}
|
||||
let target = session.suggested_path().unwrap()[0].clone();
|
||||
assert!(matches!(
|
||||
session.play_uci(&target, 1).unwrap(),
|
||||
TrainingVerdict::Right | TrainingVerdict::Finished
|
||||
));
|
||||
assert!(!session.path()[start].automatic);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_repeat_preserves_actual_route_start_and_the_next_cursor() {
|
||||
let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *");
|
||||
let mut session = (0..64)
|
||||
.map(|seed| random_session(&rep, TrainingMode::Both, seed))
|
||||
.find(|session| !session.path().is_empty())
|
||||
.expect("a deterministic mid-path start");
|
||||
let initial_scope = session.scope().clone();
|
||||
let initial_context = session.path().to_vec();
|
||||
let selected = session.suggested_path().unwrap().to_vec();
|
||||
for (index, mv) in selected.iter().enumerate() {
|
||||
session.play_uci(mv, index as i64).unwrap();
|
||||
}
|
||||
assert!(session.is_done());
|
||||
let completed_path = session.path().to_vec();
|
||||
let completed_route = random_route(&session);
|
||||
let before_repeat = serde_json::to_vec(session.stats()).unwrap();
|
||||
|
||||
session.restart(10).unwrap();
|
||||
assert_eq!(session.scope(), &initial_scope);
|
||||
assert_eq!(session.path(), initial_context);
|
||||
assert_eq!(serde_json::to_vec(session.stats()).unwrap(), before_repeat);
|
||||
for (index, mv) in selected.iter().enumerate() {
|
||||
session.play_uci(mv, 10 + index as i64).unwrap();
|
||||
}
|
||||
assert_eq!(session.path(), completed_path);
|
||||
|
||||
session.next_path(20).unwrap();
|
||||
let next = random_route(&session);
|
||||
assert_ne!(next, completed_route);
|
||||
assert!(
|
||||
RepertoireTree::new(&rep)
|
||||
.training_paths(&TrainingScope::whole())
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|path| path.moves == next)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_practice_path_count_change_starts_a_fresh_complete_cycle() {
|
||||
let rep = repertoire("1. e4 (1. d4 d5) e5 *");
|
||||
let mut initial = random_session(&rep, TrainingMode::Both, 7);
|
||||
initial.next_path(1).unwrap();
|
||||
let before = serde_json::to_value(initial.stats()).unwrap();
|
||||
let old_seed = before["random_practice_cursors"][0]["seed"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let stats = initial.into_stats();
|
||||
let mut expanded = rep.clone();
|
||||
expanded.pgn = chess_core::parse_str("1. e4 (1. d4 d5) (1. c4 e5) (1. Nf3 Nf6) e5 (1... c5) *")
|
||||
.game
|
||||
.to_pgn();
|
||||
let mut session = TrainingSession::scoped_random_with_seed(
|
||||
&expanded,
|
||||
TrainingScope::whole(),
|
||||
TrainingMode::Both,
|
||||
stats,
|
||||
2,
|
||||
7,
|
||||
)
|
||||
.unwrap();
|
||||
let after = serde_json::to_value(session.stats()).unwrap();
|
||||
assert_ne!(
|
||||
after["random_practice_cursors"][0]["seed"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
old_seed
|
||||
);
|
||||
assert_eq!(after["random_practice_cursors"][0]["position"], 1);
|
||||
assert_eq!(after["random_practice_cursors"][0]["count"], 5);
|
||||
|
||||
let mut routes = vec![random_route(&session)];
|
||||
for now in 3..7 {
|
||||
session.next_path(now).unwrap();
|
||||
routes.push(random_route(&session));
|
||||
}
|
||||
let unique: std::collections::BTreeSet<Vec<String>> = routes.into_iter().collect();
|
||||
assert_eq!(unique.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_practice_reads_old_stats_without_the_random_cursor_field() {
|
||||
let rep = repertoire("1. e4 e5 (1... c5) *");
|
||||
let mut old = serde_json::to_value(StatsData::default()).unwrap();
|
||||
assert!(
|
||||
old.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("random_practice_cursors")
|
||||
.is_some()
|
||||
);
|
||||
let stats: StatsData = serde_json::from_value(old).unwrap();
|
||||
let session = TrainingSession::scoped_random_with_seed(
|
||||
&rep,
|
||||
TrainingScope::whole(),
|
||||
TrainingMode::Both,
|
||||
stats,
|
||||
0,
|
||||
11,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(session.suggested_path().is_some());
|
||||
let saved = serde_json::to_value(session.stats()).unwrap();
|
||||
assert_eq!(saved["random_practice_cursors"][0]["position"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_both_result_finishes_on_the_real_last_ply_beyond_legacy_depth() {
|
||||
let mut rep = repertoire("1. e4 e5 2. Nf3 Nc6 *");
|
||||
rep.max_plies = 1;
|
||||
let mut session = (0..64)
|
||||
.map(|seed| random_session(&rep, TrainingMode::Both, seed))
|
||||
.find(|session| {
|
||||
random_route(session).len() == 4 && session.suggested_path().unwrap().len() == 1
|
||||
})
|
||||
.expect("a deterministic start at the final ply");
|
||||
assert_eq!(session.path().len(), 3);
|
||||
assert!(session.path().iter().all(|played| played.automatic));
|
||||
assert_eq!(
|
||||
session.play_uci("b8c6", 1).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
assert_eq!(session.path().len(), 4);
|
||||
assert_eq!(session.path().last().unwrap().uci, "b8c6");
|
||||
assert!(!session.path().last().unwrap().automatic);
|
||||
let record = session
|
||||
.stats()
|
||||
.runs(&rep.id, TrainingMode::Both)
|
||||
.unwrap()
|
||||
.recent
|
||||
.last()
|
||||
.unwrap();
|
||||
assert_eq!(record.path, strings(&["b8c6"]));
|
||||
assert_eq!(record.automatic_moves, 3);
|
||||
assert_eq!(record.user_attempts, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_scoped_start_never_escapes_the_base_end_or_creates_an_invalid_scope() {
|
||||
let rep = repertoire("1. e4 e5 2. Nf3 Nc6 (2... Nf6) 3. Bb5 a6 *");
|
||||
let prefix = strings(&["e2e4", "e7e5", "g1f3"]);
|
||||
let end = strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]);
|
||||
let base = TrainingScope::between(prefix.clone(), end.clone());
|
||||
let mut saw_short = false;
|
||||
let mut saw_end = false;
|
||||
for seed in 0..64 {
|
||||
let session = TrainingSession::scoped_random_with_seed(
|
||||
&rep,
|
||||
base.clone(),
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
0,
|
||||
seed,
|
||||
)
|
||||
.unwrap();
|
||||
let route = random_route(&session);
|
||||
assert!(route.starts_with(&prefix));
|
||||
assert!(route.len() <= end.len());
|
||||
assert_eq!(session.scope().end_prefix.as_ref(), Some(&route));
|
||||
saw_short |= route.len() < end.len();
|
||||
saw_end |= route == end;
|
||||
}
|
||||
assert!(saw_short && saw_end);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_practice_pgn_fingerprint_change_restarts_the_cycle_at_the_same_count() {
|
||||
let rep = repertoire("1. e4 (1. d4 d5) e5 *");
|
||||
let initial = random_session(&rep, TrainingMode::Both, 19);
|
||||
let before = serde_json::to_value(initial.stats()).unwrap();
|
||||
let old_seed = before["random_practice_cursors"][0]["seed"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let old_fingerprint = before["random_practice_cursors"][0]["fingerprint"].clone();
|
||||
assert_eq!(before["random_practice_cursors"][0]["position"], 1);
|
||||
assert_eq!(before["random_practice_cursors"][0]["count"], 2);
|
||||
|
||||
let mut changed = rep.clone();
|
||||
changed.pgn = chess_core::parse_str("1. c4 (1. Nf3 Nf6) e5 *")
|
||||
.game
|
||||
.to_pgn();
|
||||
let mut session = TrainingSession::scoped_random_with_seed(
|
||||
&changed,
|
||||
TrainingScope::whole(),
|
||||
TrainingMode::Both,
|
||||
initial.into_stats(),
|
||||
1,
|
||||
19,
|
||||
)
|
||||
.unwrap();
|
||||
let after = serde_json::to_value(session.stats()).unwrap();
|
||||
assert_eq!(after["random_practice_cursors"][0]["count"], 2);
|
||||
assert_eq!(after["random_practice_cursors"][0]["position"], 1);
|
||||
assert_ne!(
|
||||
after["random_practice_cursors"][0]["seed"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
old_seed
|
||||
);
|
||||
assert_ne!(
|
||||
after["random_practice_cursors"][0]["fingerprint"],
|
||||
old_fingerprint
|
||||
);
|
||||
let first = random_route(&session);
|
||||
session.next_path(2).unwrap();
|
||||
assert_ne!(random_route(&session), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_practice_cursor_without_fingerprint_safely_starts_a_new_cycle() {
|
||||
let rep = repertoire("1. e4 (1. d4 d5) e5 *");
|
||||
let initial = random_session(&rep, TrainingMode::Both, 23);
|
||||
let mut old = serde_json::to_value(initial.stats()).unwrap();
|
||||
let cursor = old["random_practice_cursors"][0].as_object_mut().unwrap();
|
||||
assert!(cursor.remove("fingerprint").is_some());
|
||||
let old_seed = cursor["seed"].as_u64().unwrap();
|
||||
assert_eq!(cursor["position"], 1);
|
||||
let stats: StatsData = serde_json::from_value(old).unwrap();
|
||||
|
||||
let session = TrainingSession::scoped_random_with_seed(
|
||||
&rep,
|
||||
TrainingScope::whole(),
|
||||
TrainingMode::Both,
|
||||
stats,
|
||||
1,
|
||||
23,
|
||||
)
|
||||
.unwrap();
|
||||
let after = serde_json::to_value(session.stats()).unwrap();
|
||||
assert!(after["random_practice_cursors"][0]["fingerprint"].is_number());
|
||||
assert_eq!(after["random_practice_cursors"][0]["position"], 1);
|
||||
assert_ne!(
|
||||
after["random_practice_cursors"][0]["seed"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
old_seed
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ pub use model::{
|
|||
};
|
||||
pub use scope::{TrainingScope, TrainingScopeKey};
|
||||
pub use session::{
|
||||
FirstMoveChooser, MoveChooser, PlayedMove, SessionAttempt, SessionError, TrainingSession,
|
||||
TrainingVerdict,
|
||||
FirstMoveChooser, MoveChooser, PlayedMove, PreparedNextPath, SessionAttempt, SessionError,
|
||||
TrainingSession, TrainingVerdict,
|
||||
};
|
||||
pub use stats::{
|
||||
AttemptRecord, INITIAL_INTERVAL_SECONDS, INTRODUCTION_BATCH_SIZE, MAX_INTERVAL_SECONDS,
|
||||
|
|
|
|||
|
|
@ -651,7 +651,7 @@ fn write_comment(comment: &str, out: &mut String) {
|
|||
}
|
||||
}
|
||||
|
||||
fn stable_hash(bytes: &[u8]) -> u64 {
|
||||
pub(crate) fn stable_hash(bytes: &[u8]) -> u64 {
|
||||
let mut hash = 0xcbf29ce484222325_u64;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
|
|
|
|||
|
|
@ -86,6 +86,9 @@ pub struct TrainingSession {
|
|||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
scope: TrainingScope,
|
||||
base_scope: TrainingScope,
|
||||
random_practice_seed: Option<u64>,
|
||||
repertoire_fingerprint: u64,
|
||||
srs_policy: SrsPolicy,
|
||||
tree: RepertoireTree,
|
||||
stats: StatsData,
|
||||
|
|
@ -110,6 +113,39 @@ pub struct TrainingSession {
|
|||
deferred_targets: BTreeSet<MoveKey>,
|
||||
}
|
||||
|
||||
pub struct PreparedNextPath {
|
||||
scope: TrainingScope,
|
||||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
stats: StatsData,
|
||||
random_practice_seed: Option<u64>,
|
||||
}
|
||||
|
||||
impl PreparedNextPath {
|
||||
pub fn run(self, repertoire: &Repertoire, now: i64) -> Result<TrainingSession, SessionError> {
|
||||
let Self {
|
||||
scope,
|
||||
mode,
|
||||
queue_mode,
|
||||
stats,
|
||||
random_practice_seed,
|
||||
} = self;
|
||||
if let Some(seed) = random_practice_seed {
|
||||
TrainingSession::scoped_random_seeded(repertoire, scope, mode, stats, now, seed)
|
||||
} else {
|
||||
TrainingSession::scoped_with_chooser(
|
||||
repertoire,
|
||||
scope,
|
||||
mode,
|
||||
queue_mode,
|
||||
stats,
|
||||
now,
|
||||
Box::<FirstMoveChooser>::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TrainingSession {
|
||||
pub fn new(
|
||||
repertoire: &Repertoire,
|
||||
|
|
@ -128,6 +164,56 @@ impl TrainingSession {
|
|||
)
|
||||
}
|
||||
|
||||
pub fn new_random(
|
||||
repertoire: &Repertoire,
|
||||
mode: TrainingMode,
|
||||
stats: StatsData,
|
||||
now: i64,
|
||||
) -> Result<Self, SessionError> {
|
||||
Self::scoped_random(repertoire, TrainingScope::whole(), mode, stats, now)
|
||||
}
|
||||
|
||||
pub fn scoped_random(
|
||||
repertoire: &Repertoire,
|
||||
scope: TrainingScope,
|
||||
mode: TrainingMode,
|
||||
stats: StatsData,
|
||||
now: i64,
|
||||
) -> Result<Self, SessionError> {
|
||||
Self::scoped_random_seeded(repertoire, scope, mode, stats, now, random_seed())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scoped_random_with_seed(
|
||||
repertoire: &Repertoire,
|
||||
scope: TrainingScope,
|
||||
mode: TrainingMode,
|
||||
stats: StatsData,
|
||||
now: i64,
|
||||
seed: u64,
|
||||
) -> Result<Self, SessionError> {
|
||||
Self::scoped_random_seeded(repertoire, scope, mode, stats, now, seed)
|
||||
}
|
||||
|
||||
fn scoped_random_seeded(
|
||||
repertoire: &Repertoire,
|
||||
scope: TrainingScope,
|
||||
mode: TrainingMode,
|
||||
stats: StatsData,
|
||||
now: i64,
|
||||
seed: u64,
|
||||
) -> Result<Self, SessionError> {
|
||||
Self::build(
|
||||
repertoire,
|
||||
scope,
|
||||
mode,
|
||||
QueueMode::Practice,
|
||||
stats,
|
||||
now,
|
||||
(None, Box::<FirstMoveChooser>::default(), Some(seed)),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn with_chooser(
|
||||
repertoire: &Repertoire,
|
||||
mode: TrainingMode,
|
||||
|
|
@ -211,7 +297,7 @@ impl TrainingSession {
|
|||
queue_mode,
|
||||
stats,
|
||||
now,
|
||||
(None, chooser),
|
||||
(None, chooser, None),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -231,7 +317,7 @@ impl TrainingSession {
|
|||
QueueMode::SpacedRepetition,
|
||||
stats,
|
||||
now,
|
||||
(Some(policy), chooser),
|
||||
(Some(policy), chooser, None),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -242,15 +328,21 @@ impl TrainingSession {
|
|||
queue_mode: QueueMode,
|
||||
stats: StatsData,
|
||||
now: i64,
|
||||
options: (Option<SrsPolicy>, Box<dyn MoveChooser>),
|
||||
options: (Option<SrsPolicy>, Box<dyn MoveChooser>, Option<u64>),
|
||||
) -> Result<Self, SessionError> {
|
||||
let (policy, chooser) = options;
|
||||
let (policy, chooser, random_practice_seed) = options;
|
||||
if policy.is_some()
|
||||
&& (mode == TrainingMode::Both || queue_mode != QueueMode::SpacedRepetition)
|
||||
{
|
||||
return Err(SessionError::InvalidSrsPolicy);
|
||||
}
|
||||
let tree = RepertoireTree::new(repertoire);
|
||||
let tree = if random_practice_seed.is_some() {
|
||||
let mut full = repertoire.clone();
|
||||
full.max_plies = u32::MAX;
|
||||
RepertoireTree::new(&full)
|
||||
} else {
|
||||
RepertoireTree::new(repertoire)
|
||||
};
|
||||
let current = tree
|
||||
.scope_anchor(&scope)
|
||||
.map_err(SessionError::InvalidScope)?;
|
||||
|
|
@ -259,7 +351,10 @@ impl TrainingSession {
|
|||
repertoire_id: repertoire.id.clone(),
|
||||
mode,
|
||||
queue_mode,
|
||||
base_scope: scope.clone(),
|
||||
scope,
|
||||
random_practice_seed,
|
||||
repertoire_fingerprint: super::model::stable_hash(repertoire.pgn.as_bytes()),
|
||||
srs_policy,
|
||||
stats,
|
||||
chooser,
|
||||
|
|
@ -510,7 +605,7 @@ impl TrainingSession {
|
|||
}
|
||||
|
||||
/// Repeats the same proposed path (or restarts the current one-side queue). It does
|
||||
/// not advance the Both path cursor and never counts an unfinished run as complete.
|
||||
/// not advance a path cursor and never counts an unfinished run as complete.
|
||||
pub fn restart(&mut self, now: i64) -> Result<(), SessionError> {
|
||||
if self.queue_mode == QueueMode::Practice && !self.actual_path.is_empty() {
|
||||
self.suggested_path = Some(TrainingPath {
|
||||
|
|
@ -521,6 +616,28 @@ impl TrainingSession {
|
|||
self.initialize(now, false)
|
||||
}
|
||||
|
||||
/// Captures the inputs for a next-path run without changing this session. The
|
||||
/// expensive tree traversal happens only when `PreparedNextPath::run` is called.
|
||||
pub fn prepare_next_path(&self) -> Result<PreparedNextPath, SessionError> {
|
||||
if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice {
|
||||
return Err(SessionError::InvalidQueueMode(
|
||||
"next_path is available in branch practice or Both mode",
|
||||
));
|
||||
}
|
||||
let scope = if self.random_practice_seed.is_some() {
|
||||
&self.base_scope
|
||||
} else {
|
||||
&self.scope
|
||||
};
|
||||
Ok(PreparedNextPath {
|
||||
scope: scope.clone(),
|
||||
mode: self.mode,
|
||||
queue_mode: self.queue_mode,
|
||||
stats: self.stats.clone(),
|
||||
random_practice_seed: self.random_practice_seed,
|
||||
})
|
||||
}
|
||||
|
||||
/// Selects the next proposed root/scope-to-boundary path. Enabled deviations remain
|
||||
/// free; the actual path, rather than this proposal, receives completion statistics.
|
||||
pub fn next_path(&mut self, now: i64) -> Result<(), SessionError> {
|
||||
|
|
@ -529,6 +646,9 @@ impl TrainingSession {
|
|||
"next_path is available in branch practice or Both mode",
|
||||
));
|
||||
}
|
||||
if self.random_practice_seed.is_some() {
|
||||
self.scope = self.base_scope.clone();
|
||||
}
|
||||
self.reset_run()?;
|
||||
self.suggested_path = None;
|
||||
self.initialize(now, true)
|
||||
|
|
@ -570,10 +690,14 @@ impl TrainingSession {
|
|||
fn initialize(&mut self, now: i64, select_path: bool) -> Result<(), SessionError> {
|
||||
if self.queue_mode == QueueMode::Practice {
|
||||
if select_path {
|
||||
self.suggested_path = self
|
||||
.stats
|
||||
.next_practice_path(&self.tree, &self.repertoire_id, self.mode, &self.scope)
|
||||
.map_err(SessionError::InvalidScope)?;
|
||||
if self.random_practice_seed.is_some() {
|
||||
self.select_random_path()?;
|
||||
} else {
|
||||
self.suggested_path = self
|
||||
.stats
|
||||
.next_practice_path(&self.tree, &self.repertoire_id, self.mode, &self.scope)
|
||||
.map_err(SessionError::InvalidScope)?;
|
||||
}
|
||||
}
|
||||
self.prepare_scope_start()?;
|
||||
if self.suggested_path.is_none() {
|
||||
|
|
@ -614,6 +738,55 @@ impl TrainingSession {
|
|||
}
|
||||
}
|
||||
|
||||
fn select_random_path(&mut self) -> Result<(), SessionError> {
|
||||
let seed = self
|
||||
.random_practice_seed
|
||||
.ok_or(SessionError::InvalidQueueMode(
|
||||
"random practice seed is missing",
|
||||
))?;
|
||||
let selected = self
|
||||
.stats
|
||||
.next_random_practice_path(
|
||||
&self.tree,
|
||||
&self.repertoire_id,
|
||||
self.mode,
|
||||
&self.base_scope,
|
||||
self.repertoire_fingerprint,
|
||||
seed,
|
||||
)
|
||||
.map_err(SessionError::InvalidScope)?;
|
||||
let Some(selected) = selected else {
|
||||
self.scope = self.base_scope.clone();
|
||||
self.suggested_path = None;
|
||||
return Ok(());
|
||||
};
|
||||
let prefix_moves = selected
|
||||
.path
|
||||
.moves
|
||||
.get(..=selected.start)
|
||||
.ok_or(SessionError::MissingTargetPath)?;
|
||||
let suggested = selected
|
||||
.path
|
||||
.moves
|
||||
.get(selected.start..)
|
||||
.ok_or(SessionError::MissingTargetPath)?
|
||||
.to_vec();
|
||||
let mut prefix = self.base_scope.parent_prefix().to_vec();
|
||||
prefix.extend(prefix_moves.iter().cloned());
|
||||
let end_prefix = self.base_scope.end_prefix.as_ref().map(|_| {
|
||||
let mut end = self.base_scope.parent_prefix().to_vec();
|
||||
end.extend(selected.path.moves.iter().cloned());
|
||||
end
|
||||
});
|
||||
self.scope = TrainingScope {
|
||||
prefix,
|
||||
end_prefix,
|
||||
include_context: true,
|
||||
};
|
||||
self.suggested_path = Some(TrainingPath { moves: suggested });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare_scope_start(&mut self) -> Result<(), SessionError> {
|
||||
let anchor = self
|
||||
.tree
|
||||
|
|
@ -981,3 +1154,9 @@ impl TrainingSession {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn random_seed() -> u64 {
|
||||
use std::hash::BuildHasher;
|
||||
|
||||
std::collections::hash_map::RandomState::new().hash_one(0u8)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use chess_core::shakmaty::Color;
|
||||
use chess_core::shakmaty::{Color, Position};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::model::RepertoireId;
|
||||
|
|
@ -263,6 +263,23 @@ struct PathReviewCursor {
|
|||
next: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct RandomPracticeCursor {
|
||||
repertoire_id: RepertoireId,
|
||||
mode: TrainingMode,
|
||||
scope: TrainingScopeKey,
|
||||
seed: u64,
|
||||
position: usize,
|
||||
count: usize,
|
||||
#[serde(default)]
|
||||
fingerprint: Option<u64>,
|
||||
}
|
||||
|
||||
pub(crate) struct RandomPracticePath {
|
||||
pub path: TrainingPath,
|
||||
pub start: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct StatsData {
|
||||
|
|
@ -276,6 +293,7 @@ pub struct StatsData {
|
|||
review_cursors: Vec<ReviewCursor>,
|
||||
path_review_cursors: Vec<PathReviewCursor>,
|
||||
practice_path_cursors: Vec<ReviewCursor>,
|
||||
random_practice_cursors: Vec<RandomPracticeCursor>,
|
||||
}
|
||||
|
||||
impl Default for StatsData {
|
||||
|
|
@ -290,6 +308,7 @@ impl Default for StatsData {
|
|||
review_cursors: Vec::new(),
|
||||
path_review_cursors: Vec::new(),
|
||||
practice_path_cursors: Vec::new(),
|
||||
random_practice_cursors: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -310,6 +329,8 @@ impl StatsData {
|
|||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
self.practice_path_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
self.random_practice_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &MoveKey) -> Option<&MoveStats> {
|
||||
|
|
@ -562,6 +583,111 @@ impl StatsData {
|
|||
Ok(chosen)
|
||||
}
|
||||
|
||||
pub(crate) fn next_random_practice_path(
|
||||
&mut self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
scope: &TrainingScope,
|
||||
repertoire_fingerprint: u64,
|
||||
initial_seed: u64,
|
||||
) -> Result<Option<RandomPracticePath>, String> {
|
||||
use std::ops::ControlFlow;
|
||||
|
||||
let anchor = tree.scope_anchor(scope)?;
|
||||
let start_turn = tree
|
||||
.position(anchor)
|
||||
.map(|position| position.turn())
|
||||
.ok_or_else(|| "scope start position is missing".to_owned())?;
|
||||
let mut count = Some(0usize);
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
if eligible_target_count(mode, start_turn, moves.len()) == 0 {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
count = count.and_then(|count| count.checked_add(1));
|
||||
if count.is_none() {
|
||||
ControlFlow::Break(())
|
||||
} else {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
})?;
|
||||
let count =
|
||||
count.ok_or_else(|| "training path count exceeds the platform limit".to_owned())?;
|
||||
let scope_key = scope.key();
|
||||
let existing = self.random_practice_cursors.iter().position(|cursor| {
|
||||
&cursor.repertoire_id == repertoire_id
|
||||
&& cursor.mode == mode
|
||||
&& cursor.scope == scope_key
|
||||
});
|
||||
let is_new = existing.is_none();
|
||||
let index = existing.unwrap_or_else(|| {
|
||||
self.random_practice_cursors.push(RandomPracticeCursor {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
scope: scope_key,
|
||||
seed: initial_seed,
|
||||
position: 0,
|
||||
count: 0,
|
||||
fingerprint: Some(repertoire_fingerprint),
|
||||
});
|
||||
self.random_practice_cursors.len() - 1
|
||||
});
|
||||
let cursor = &mut self.random_practice_cursors[index];
|
||||
if !is_new
|
||||
&& (cursor.fingerprint != Some(repertoire_fingerprint)
|
||||
|| cursor.count != count
|
||||
|| cursor.position >= count)
|
||||
{
|
||||
cursor.seed = next_cycle_seed(cursor.seed);
|
||||
cursor.position = 0;
|
||||
}
|
||||
cursor.fingerprint = Some(repertoire_fingerprint);
|
||||
cursor.count = count;
|
||||
if count == 0 {
|
||||
cursor.position = 0;
|
||||
return Ok(None);
|
||||
}
|
||||
if cursor.position >= count {
|
||||
cursor.position = 0;
|
||||
}
|
||||
|
||||
let position = cursor.position;
|
||||
let seed = cursor.seed;
|
||||
let step = coprime_step(seed ^ 0xa076_1d64_78bd_642f, count);
|
||||
let offset = (mix64(seed ^ 0xe703_7ed1_a0b4_28db) as u128 % count as u128) as usize;
|
||||
let selected_index =
|
||||
((step as u128 * position as u128 + offset as u128) % count as u128) as usize;
|
||||
let start_seed = mix64(seed ^ (position as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15));
|
||||
let mut order = 0usize;
|
||||
let mut chosen = None;
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
let eligible = eligible_target_count(mode, start_turn, moves.len());
|
||||
if eligible == 0 {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
if order == selected_index {
|
||||
let start_order = (start_seed as usize) % eligible;
|
||||
chosen = eligible_target_index(mode, start_turn, moves.len(), start_order).map(
|
||||
|start| RandomPracticePath {
|
||||
path: TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
},
|
||||
start,
|
||||
},
|
||||
);
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
order += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
if chosen.is_some() {
|
||||
cursor.position = cursor.position.saturating_add(1);
|
||||
Ok(chosen)
|
||||
} else {
|
||||
Err("random training path selection is inconsistent".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects one route without materializing the complete path queue. Ordered
|
||||
/// review stops as soon as its cursor is reached; only wrapping needs a second pass.
|
||||
pub fn next_training_path(
|
||||
|
|
@ -829,6 +955,9 @@ impl StatsData {
|
|||
self.practice_path_cursors.sort_by(|a, b| {
|
||||
(&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope))
|
||||
});
|
||||
self.random_practice_cursors.sort_by(|a, b| {
|
||||
(&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope))
|
||||
});
|
||||
self.path_review_cursors
|
||||
.sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope)));
|
||||
}
|
||||
|
|
@ -844,3 +973,69 @@ impl StatsData {
|
|||
&mut self.move_stats[index]
|
||||
}
|
||||
}
|
||||
|
||||
fn eligible_target_count(mode: TrainingMode, start_turn: Color, plies: usize) -> usize {
|
||||
let Some(user_color) = mode.user_color() else {
|
||||
return plies;
|
||||
};
|
||||
let first = usize::from(start_turn != user_color);
|
||||
if plies <= first {
|
||||
0
|
||||
} else {
|
||||
(plies - first).div_ceil(2)
|
||||
}
|
||||
}
|
||||
|
||||
fn eligible_target_index(
|
||||
mode: TrainingMode,
|
||||
start_turn: Color,
|
||||
plies: usize,
|
||||
order: usize,
|
||||
) -> Option<usize> {
|
||||
let mut remaining = order;
|
||||
for index in 0..plies {
|
||||
let turn = if index % 2 == 0 {
|
||||
start_turn
|
||||
} else {
|
||||
start_turn.other()
|
||||
};
|
||||
if mode.user_color().is_none_or(|color| color == turn) {
|
||||
if remaining == 0 {
|
||||
return Some(index);
|
||||
}
|
||||
remaining -= 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn coprime_step(seed: u64, count: usize) -> usize {
|
||||
if count == 1 {
|
||||
return 0;
|
||||
}
|
||||
let mut step = (mix64(seed) % count as u64) as usize;
|
||||
while gcd(step, count) != 1 {
|
||||
step = (step + 1) % count;
|
||||
}
|
||||
step
|
||||
}
|
||||
|
||||
fn gcd(mut left: usize, mut right: usize) -> usize {
|
||||
while right != 0 {
|
||||
let remainder = left % right;
|
||||
left = right;
|
||||
right = remainder;
|
||||
}
|
||||
left
|
||||
}
|
||||
|
||||
fn next_cycle_seed(seed: u64) -> u64 {
|
||||
mix64(seed ^ 0x8ebc_6af0_9c88_c6e3)
|
||||
}
|
||||
|
||||
fn mix64(mut value: u64) -> u64 {
|
||||
value = value.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
value ^ (value >> 31)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -297,3 +297,16 @@
|
|||
сценарий с сохранением выбранного цвета. Позднее явно выбранный режим повторения
|
||||
сохраняется; PGN и история попыток при миграции не меняются.
|
||||
- Android остаётся на старом линейном API; web новый вход не получает.
|
||||
|
||||
## Простая случайная тренировка вариантов (2026-11-03)
|
||||
|
||||
Владелец отменил ручные параметры и расширенные режимы в desktop-интерфейсе. Это решение имеет приоритет над пунктами про глубину, disabled, scope и SRS выше; внутренние совместимые API и старая статистика могут остаться, но скрыто ограничивать тренировку не должны.
|
||||
|
||||
- В репертуаре остаются только выбор цвета `Белые / Чёрные / Оба`, число доступных вариантов и запуск. Настроек глубины, области, отключения веток и «Пройти варианты / Повторять отдельные позиции» нет. Видимое дерево ходов также удалено; PGN-дерево остаётся внутренней моделью.
|
||||
- В самой тренировке текстовые ходы также не показываются: ни SAN/номера, ни отметки ошибок у ходов, ни отдельная панель нотации. Повторное уточнение владельца 2026-11-03 выбрало удаление, а не копирование нотации из экрана партии. Просматривать уже показанные позиции можно только на доске прежними кнопками/клавишами; внутренний путь для механики сохраняется.
|
||||
- Тренируются все варианты целиком, без лимита 20 полуходов. Старые `max_plies` и `disabled_prefixes` при загрузке библиотеки снимаются; PGN и исходные файлы не меняются.
|
||||
- Очередь случайная. Полный маршрут не повторяется, пока пользователь не прошёл остальные маршруты текущего круга; затем начинается новый случайный круг. Общий префикс разных веток не считается пересечением: иначе невозможно пройти все ветки.
|
||||
- Проход может начинаться не с первого хода. Программа автоматически показывает предыдущий участок как контекст и предлагает продолжить вариант; для White/Black первая пользовательская позиция соответствует выбранному цвету, для Both пользователь продолжает за обе стороны.
|
||||
- На развилке по-прежнему принимается любой ход из PGN. После завершения две отдельные операции: «Повторить путь» — тот же фактический маршрут с тем же началом, без продвижения очереди; «Следующая ветка» — новый непройденный маршрут текущего круга.
|
||||
- В библиотеке остаются `Название | Варианты | меню`. Число вариантов — доступные полные маршруты, а не завершённые тренировки. Колонки due удалены вместе с SRS UI; сохранённые попытки и история не стираются.
|
||||
- Случайная очередь не блокирует окно и не требует материализации всех маршрутов большого дерева. Это относится и к «Следующей ветке», не только к первому запуску. Курсор и совместимость сохранённой статистики проверяются тестами; изменение PGN начинает новый круг по fingerprint содержимого, даже если число маршрутов осталось прежним.
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@
|
|||
|
||||
Статус: **финальный рабочий дизайн для desktop-реализации**, 2026-11-02. Основание — подтверждённое решение `docs/decisions.md` «Дебютные репертуары и тренировка по дереву (2026-11-02)». Этот документ заменяет сценарий немедленного «Учить дебют до этого хода» на desktop; старый Android-тренер не меняется.
|
||||
|
||||
**Актуализация 2026-11-02:** скрытая целевая модель и `try again` из прежних разделов отменены после живого замечания владельца; действующий пользовательский путь — §20 и новое решение в `docs/decisions.md`.
|
||||
**Актуализация 2026-11-02:** скрытая целевая модель и `try again` из прежних разделов отменены после живого замечания владельца; пользовательский путь уточнён в §20.
|
||||
|
||||
**Действующая редакция 2026-11-03:** §21 и раздел «Простая случайная тренировка вариантов» в `docs/decisions.md`. Видимое дерево, глубина, disabled, область, due-колонки и выбор проход/SRS отменены владельцем; прежние разделы оставлены как история проектирования и не описывают текущий UI там, где противоречат §21.
|
||||
|
||||
Размеры ниже — логические точки egui. Подписи даны на русском; обязательные RU/EN/DE-строки — в §13. Открытых продуктовых вопросов и альтернатив для реализации нет.
|
||||
|
||||
|
|
@ -877,3 +879,40 @@ Disabled-ход и ход глубже текущего лимита в акти
|
|||
Статистика ходов отражает фактически сыгранные ответы; автоматические ходы не
|
||||
считаются попытками. Практика не меняет существующие сроки SRS. Прохождения и
|
||||
статистика веток за обе стороны обновляются и в новом основном режиме.
|
||||
|
||||
## 21. Действующее упрощение: случайный круг вариантов (2026-11-03)
|
||||
|
||||
Этот раздел заменяет прежние требования к видимому дереву, глубине, disabled, области, due-колонкам и выбору очереди. Остальные правила сохранности PGN, доски, ввода, ошибок, подсказок и статистики действуют.
|
||||
|
||||
### 21.1. Библиотека и репертуар
|
||||
|
||||
Библиотека — таблица `Название | Варианты | ⋯`. Числовые заголовки и значения выровнены по правому краю. «Варианты» — количество маршрутов, доступных тренировке, а не число завершений: у нового репертуара с двумя маршрутами сразу показано `2`. Подсчёт выполняется в фоне; во время него виден индикатор, а не прочерк, похожий на ноль.
|
||||
|
||||
На экране репертуара нет дерева ходов и ручных ограничений. Порядок элементов: название; импорт/экспорт; цвет `Белые | Чёрные | Оба`; число вариантов и основная кнопка «Начать тренировку»; компактная статистика. Глубина, область и выбор «проход / отдельные позиции» удалены, а не скрыты под дополнительным меню. Старые ограничения из JSON снимаются при загрузке, чтобы невидимо не менять содержимое тренировки.
|
||||
|
||||
### 21.2. Случайный круг и начало не с первого хода
|
||||
|
||||
- Для круга формируется случайная перестановка полных маршрутов. Каждый предлагается один раз; после последнего начинается новый круг с новой перестановкой. Повтор по желанию пользователя не считается следующим элементом очереди.
|
||||
- Два маршрута могут иметь общий префикс: это разные варианты, а не ошибочное пересечение. Не повторяется именно полный маршрут.
|
||||
- Начало выбирается случайно среди позиций маршрута, где есть продолжение для выбранной стороны. До неё проигрывается automatic context. Пользователь не настраивает prefix/scope и не видит сырые UCI.
|
||||
- White/Black получают первую задачу своего цвета; программа отвечает из выбранной ветки. Both получает любую позицию с продолжением и ходит за обе стороны. Пустой suffix и старт за пределами PGN недопустимы.
|
||||
- Очередь строится в фоне и при первом запуске, и при Next. Для большого дерева используются последовательный подсчёт и выбор маршрута, а не список всех путей в памяти; состояние круга сериализуется совместимо со старой статистикой. Fingerprint PGN входит в ключ круга: изменение содержимого при неизменном числе маршрутов также начинает новый круг.
|
||||
|
||||
### 21.3. Проход и результат
|
||||
|
||||
Экран прохода сохраняет доску, ошибку, подсказку и число ошибок. Автоматический префикс не считается пользовательскими попытками. Видимого «Дерева» будущих ходов нет. Текстовая нотация также полностью удалена: SAN, номера ходов, `×N`/`*` и отдельная scroll area не показываются и не резервируют место. Просмотр уже показанных позиций выполняется на доске прежним toolbar и клавишами; внутренний путь для этого и для механики сохраняется.
|
||||
|
||||
После последнего реального полухода показываются результат и два равноправно доступных действия с разным приоритетом:
|
||||
|
||||
1. Основная **«Следующая ветка»** (и Enter) выбирает следующий непройденный маршрут круга, с новым случайным началом.
|
||||
2. **«Повторить путь»** повторяет фактически сыгранный маршрут, включая выбранные пользователем отклонения, автоответы и исходную стартовую позицию. Курсор очереди не двигается.
|
||||
|
||||
«Назад к репертуару» остаётся отдельным действием. Ошибка сохранения не позволяет молча продолжить как будто данные записаны.
|
||||
|
||||
### 21.4. Обязательная приёмка этого уточнения
|
||||
|
||||
- Новый Spanish с двумя маршрутами и нулём завершений показывает `Варианты: 2`; после тренировок смысл числа не меняется.
|
||||
- Старые `max_plies=20`, disabled и SRS-настройки не ограничивают новый запуск; PGN и история попыток сохраняются.
|
||||
- На fixture минимум из трёх веток весь круг содержит каждый полный маршрут один раз; следующий круг снова содержит все. Изменение PGN корректно начинает новый круг.
|
||||
- White, Black и Both получают легальный automatic context и ход нужной стороны; доска совпадает с фактической позицией session, текстовой нотации и её пустого контейнера нет. Repeat сохраняет точный путь и старт, Next не наследует старую случайную область.
|
||||
- В RU/EN/DE, dark/light, 1400×900 и 640×480 нет удалённых контролов, обрезанных заголовков, наложений и недостижимых кнопок. Во всех режимах проверяются правильный ход, ошибка/подсказка, итог, Repeat, Next и Back.
|
||||
|
|
|
|||
|
|
@ -158,9 +158,10 @@
|
|||
- **Суть:** в ChessBase есть создание тренировочных файлов: в партию или базу ставятся позиции-задания, пользователь решает их (находит ход или ряд ходов), за решение начисляются баллы (с учётом попыток/времени), итог — счёт. Исследовать: как это устроено в ChessBase (формат «Training» в .cbh/.cbv/PGN — аннотации-вопросы, таймер, очки, подсказки), читаем ли мы такие задания уже сейчас и что с ними делаем; как сделать у нас: создание заданий из своих партий (в том числе из разбора — ошибки/!!/! как задания), решение с подсчётом баллов, статистика; связь с изучением дебюта (задача 15) и с разбором партии; компьютер и Android.
|
||||
|
||||
### 24. Тренировка по дереву вариантов из файла, как в ChessTempo (2026-10-31)
|
||||
- **Статус:** в работе (2026-11-02): владелец делегировал решения оркестратору; выбраны глубина 10 по умолчанию, статистика внутри репертуара и desktop-first.
|
||||
- **Статус:** в работе: действующий простой сценарий 2026-11-03 реализован и принят независимым tester; desktop-first, выпуск ещё не назначен. Прежние глубина/область/SRS отменены владельцем.
|
||||
- **Пересмотр сценария после живого замечания владельца (2026-11-02):** основной режим — «Пройти варианты» за выбранный цвет, без скрытых целей/try again; любой включённый ход принимается, подсказка сразу, после результата — следующая ветка. Отдельное повторение позиций также принимает альтернативы. Решение — `docs/decisions.md`, дизайн §20.
|
||||
- **Доработка 2026-11-02:** переработана вёрстка библиотеки/репертуара/тренировки; виртуализирована таблица, добавлено сворачивание RAV, индексы/счётчики/подготовка сессии вынесены в фон. Выбор пути Both — потоковый без полной материализации очереди; исправлена вставка поддерева в неверную ветку при транспозициях. Регрессионные проверки и ограничения — `docs/qa/repertoire-layout-2026-11-02.md`. Полная приёмка задачи 24 ещё не закрыта.
|
||||
- **Уточнение владельца 2026-11-03:** убрать видимое дерево, глубину, область и выбор проход/SRS; все варианты тренируются целиком. Случайный круг без повторов полных маршрутов, возможен автоматический префикс перед случайным стартом; после варианта — «Повторить путь» с тем же началом или «Следующая ветка». Позже владелец повторно подтвердил: текстовой нотации в тренировке тоже нет, просмотр позиций — только на доске. Решение — `docs/decisions.md`, действующий дизайн — `docs/design/repertoire-training.md` §21. Также исправлен обманчивый прочерк у нового Spanish: прежняя колонка показывала завершения вместо вариантов; теперь `Название | Варианты | меню`.
|
||||
- **Суть:** ChessTempo берёт все варианты из PGN (репертуар, урок тренера) и гоняет по ним: пользователь играет свою сторону, программа отвечает ходами из дерева — не по порядку, а следуя ходам пользователя; так удобно учить разветвлённые варианты. Проблема длинных примерных партий внутри теории — слишком много позиций для проработки.
|
||||
- **Новые требования владельца (2026-11-02):** кнопка «Тренировка дебюта» рядом с «Подготовки» на экране баз; библиотека репертуаров/вариантов; вместо немедленного «Учить дебют до этого хода» — добавление линии в репертуар; одноцветный режим ChessTempo и дополнительный режим за оба цвета, где любой ход вне включённых веток — ошибка; полезная статистика. Одноцветный режим пересматривает прежний запрет в `docs/decisions.md`.
|
||||
- **Исследования:** `docs/research/chesstempo-opening-trainer.md` (официальные источники ChessTempo, 33 критерия), `docs/research/opening-trainer-current.md` (текущий код, reuse/gaps, миграция). Независимый QA подтвердил ключевые факты и различие моделей target-хода и режима за обе стороны.
|
||||
|
|
@ -208,6 +209,31 @@
|
|||
- **Суть (владелец):** строки `30 ?! · 10 ? · 13 ?? в 71 % партий` / `25 ?! · 10 ? · 9 ?? в 70 % партий` «поехали». Счётчики и процент стояли в одном `horizontal`, поэтому процент смещался с разрядностью чисел; расчёт ширины также не совпадал с реальным рендером.
|
||||
- **Дизайн:** `docs/design/opponent-prep.md` §3.5. Порядок `?! · ? · ??`, нулевые типы пропускаются, при нуле — `no errors` без фиктивного процента. Исправленная в задаче 28 сетка цвета/числа/счёта сохранена.
|
||||
|
||||
### 33. Изучить Lotus Chess и оценить идеи для ChessPenguin (2026-11-03)
|
||||
- **Статус:** новая.
|
||||
- **Добавлено:** 2026-11-03.
|
||||
- **Суть (владелец):** изучить программу Lotus Chess, посмотреть, какие решения и идеи могут пригодиться в ChessPenguin. В частности, ходы не обязательно воспроизводить с начала партии: алгоритм может дать позицию из базы вариантов, и пользователь должен продолжить игру из неё.
|
||||
- **С чего начать:** найти официальные материалы и актуальную версию Lotus Chess; изучить основные сценарии, интерфейс и функции, включая выбор/подачу позиции для продолжения; сопоставить с возможностями ChessPenguin; записать источники, полезные идеи и стоимость их реализации. Пока ничего не переносить без отдельного решения.
|
||||
|
||||
### 34. Проверить поддержку новых форматов ChessBase (2026-11-03)
|
||||
- **Статус:** новая; нужна техническая проверка.
|
||||
- **Добавлено:** 2026-11-03.
|
||||
- **Суть (владелец):** выяснить, можем ли мы открывать новые форматы ChessBase; владелец помнит, что «со второй версией» что-то менялось, но точный номер версии и формат нужно установить.
|
||||
- **С чего начать:** уточнить по документации/релизам ChessBase, с какого выпуска и какие форматы или версии `.cbh`/`.cbv` отличаются; проверить текущий импортёр (`crates/chess-import`) на легальных контрольных файлах разных поколений; зафиксировать поддерживаемые версии, ограничения и варианты реализации. Исходные файлы использовать только для чтения.
|
||||
|
||||
### 35. Android: вставка PGN из буфера обмена для просмотра и анализа (2026-11-03)
|
||||
- **Статус:** новая; исследовать платформенные ограничения и сценарий.
|
||||
- **Добавлено:** 2026-11-03.
|
||||
- **Суть (владелец):** при запуске мобильного приложения проверять, содержит ли буфер обмена PGN; дать возможность вставить его в ChessPenguin, открыть партию и затем анализировать её.
|
||||
- **С чего начать:** изучить ограничения Android на чтение буфера при запуске/возврате приложения; продумать понятное предложение «Открыть PGN из буфера» без автоматического импорта или изменения файлов; проверить текст PGN и цепочки ходов, несколько партий, некорректный текст, приватность и доступность действия после запуска; найти подходящее место в мобильном интерфейсе и связать с существующими просмотром/анализом партии.
|
||||
|
||||
### 36. Строить дебютный репертуар из партий большой базы (2026-11-03)
|
||||
- **Статус:** новая идея владельца; исследовать и спроектировать.
|
||||
- **Добавлено:** 2026-11-03.
|
||||
- **Связано:** задачи 24 (тренировка по дереву) и 19 (дебютный репертуар).
|
||||
- **Суть (владелец):** открыть большую базу партий, выбрать позицию в дебюте (например, Найдорф после `…a6`) и глубину (например, до 15-го хода). Программа проходит партии из этой базы, находит продолжения из позиции до заданной глубины и собирает из них дерево вариантов в дебютный репертуар. Затем пользователь учит это дерево в режиме тренировки по вариантам, как в ChessTempo.
|
||||
- **С чего начать:** проверить поиск и выборку партий из существующей базы по позиции/префиксу; уточнить отбор (все партии или только топовых игроков/партий, минимум партий на продолжение, популярность/период), смысл глубины «до 15-го хода» для обеих сторон, контроль взрыва редких веток и повторных позиций; предусмотреть просмотр статистики ходов и источников перед добавлением. Добавление должно менять только репертуар, не исходную базу; повторный сбор — слияние/обновление вариантов без потери аннотаций и статистики тренировки.
|
||||
|
||||
## Сделано
|
||||
|
||||
(пусто)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
Проверена незакоммиченная реализация поверх `4eb0822` (2.1.5).
|
||||
Это проверка доработки, не закрытие всей приёмки задачи 24.
|
||||
|
||||
**Актуальность на 2026-11-03:** это исторический отчёт о прежнем UI с деревом, глубиной, областью и очередями. Действующий сценарий — `docs/design/repertoire-training.md` §21: простой случайный круг полных вариантов. Перечисленные ниже снимки и результаты не являются приёмкой нового сценария.
|
||||
|
||||
## Изменения
|
||||
|
||||
- Библиотека: виртуализированная таблица с постоянными колонками; длинные названия
|
||||
|
|
@ -86,3 +88,52 @@ Android/web в этой доработке не проверялись.
|
|||
по-прежнему требуют полного обхода графа; подсчёт выполняется в фоне. Загрузка
|
||||
JSON-хранилища и атомарный commit остаются синхронными. Эта доработка не является
|
||||
доказательством производительности на произвольно большом транспозиционном графе.
|
||||
|
||||
## Действующий простой сценарий, 2026-11-03
|
||||
|
||||
Проверялась реализация §21 `docs/design/repertoire-training.md`: без видимого дерева,
|
||||
глубины, области и SRS UI; полные PGN-варианты, случайный круг, automatic context,
|
||||
Next/Repeat. Изменения ещё не включены в выпуск.
|
||||
|
||||
### Проверки оркестратора
|
||||
|
||||
- `cargo fmt --all -- --check`, `git diff --check` — успешно.
|
||||
- `cargo clippy -p chesspenguin -p trainer --all-targets --locked -- -D warnings` — успешно.
|
||||
- Полный `cargo test --workspace --locked --quiet` — успешно; desktop **121 passed, 4 ignored**,
|
||||
trainer **63 passed**. Остальные пакеты также зелёные.
|
||||
- `cargo check -p chesspenguin-web --target wasm32-unknown-unknown --locked` — успешно.
|
||||
- Изолированные XDG, собранное приложение X11: импорт Spanish; библиотека и репертуар
|
||||
RU dark 1400×900; библиотека EN light 640×480; White result/Next/Repeat и error/hint;
|
||||
Black DE light result 640×480; Both EN dark result 640×480. Все финальные снимки
|
||||
просмотрены: удалённых контролов и наложений нет, Next/Repeat/Back видны, accepted
|
||||
message имеет обычный цвет текста.
|
||||
|
||||
### Независимая приёмка
|
||||
|
||||
Отдельный tester проверил async Next/generation, сохранение cursor без хода, Repeat
|
||||
фактического пути, fingerprint при неизменном числе маршрутов, eligible White/Black/Both,
|
||||
перестановку круга, снятие старых ограничений, ошибку миграции и пустой запуск. Просмотрел
|
||||
восемь основных снимков и независимо запустил `cargo test -p trainer -p chesspenguin
|
||||
--locked --quiet`: **121 desktop + 63 trainer passed**. Вердикт — **принято, подтверждённых
|
||||
дефектов в проверенных путях нет**.
|
||||
|
||||
Не выполнялась исчерпывающая матрица всех состояний × языков × тем × размеров и все
|
||||
динамические действия в каждой комбинации. Независимый tester использовал предоставленные
|
||||
снимки, повторный X11 не запускал; оркестратор позже обновил Black/Both снимки и проверил
|
||||
error/hint на финальном коде. Android/web UI не менялись; для web выполнен Rust wasm check,
|
||||
не браузерная приёмка.
|
||||
|
||||
## Удаление текстовой нотации из тренировки, 2026-11-03
|
||||
|
||||
После повторного замечания владельца из активной тренировки удалены SAN, номера ходов,
|
||||
пометки `×N`/`*`, отдельная scroll area и её зарезервированная высота. Внутренние
|
||||
`session.path`/`positions` и toolbar просмотра позиций на доске сохранены; механика не
|
||||
изменена. Аналитик подтвердил независимость механики от удалённой отрисовки, дизайнер —
|
||||
компоновку без пустого хвоста.
|
||||
|
||||
`cargo clippy -p chesspenguin --all-targets --locked -- -D warnings`, **121 desktop test**
|
||||
и `git diff --check` прошли. В изолированном XDG просмотрены активный проход и результат
|
||||
RU dark 1400×900, error/hint RU dark 640×480. Дизайнер отдельно проверил снимки и актуальный
|
||||
`side()`: текстовых ходов, вложенной прокрутки, висячего separator и зарезервированного
|
||||
контейнера нет; доска, подсказка, результат и навигация доступны. Вердикт — **принято,
|
||||
визуальных дефектов в представленных состояниях не обнаружено**.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue