Play against Maia: dialog, clocks, game screen, result strip
«⚔ Play» (Ctrl+G) opens «Play against the computer»: name and rating (optional), strength 600–2600 (or weaker/as me/stronger), colour, Lichess time controls, custom, no clock. The game screen in play mode: clock cards above and below the notation (read-only), take back, resign (abort before the first moves); no engine, analysis or editing. Maia answers in a background thread with a human-like pause bounded so she never loses on time; stale answers are dropped. Endings: mate, stalemate, no material, threefold, fifty moves, time (draw when the other side cannot mate), resignation; then the result strip (Analyse, Rematch, New game, Save to a database) and an ordinary game with the tags of a played game and [%clk]. Leaving during a game asks (resign and add / resign and leave / keep playing), the clocks wait meanwhile. maia reads the published PyTorch checkpoint directly (zip + a small pickle reader that refuses everything but tensors); maia_download fetches it on request (pinned revision, SHA-256). Dev hooks CP_PLAY, CP_PLAY_AUTO, CP_MAIA. Russian texts; the other languages follow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8b468f99a7
commit
9cd28b9039
18 changed files with 2843 additions and 151 deletions
|
|
@ -166,6 +166,12 @@ pub fn overlay_open_besides(ctx: &egui::Context, own: &[egui::Id]) -> bool {
|
|||
})
|
||||
}
|
||||
|
||||
/// What starts once the played game is closed.
|
||||
enum PlayNext {
|
||||
Rematch(crate::play::Start),
|
||||
Dialog,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum CloseIntent {
|
||||
BackToLibrary,
|
||||
|
|
@ -186,6 +192,11 @@ pub struct App {
|
|||
settings_ui: SettingsWindow,
|
||||
toast: Option<Toast>,
|
||||
own: Own,
|
||||
/// The play dialog («Play against the computer»).
|
||||
play_dialog: Option<crate::play::Dialog>,
|
||||
/// After the current game is closed: a new game against Maia (a rematch, or the
|
||||
/// dialog for a new one).
|
||||
play_next: Option<PlayNext>,
|
||||
tx: Sender<Async>,
|
||||
rx: Receiver<Async>,
|
||||
confirm_close: Option<CloseIntent>,
|
||||
|
|
@ -240,6 +251,8 @@ struct DebugStartup {
|
|||
/// (own_db.rs) after a short delay; `delete` and `chooser` without a game: the
|
||||
/// record `CP_OPEN` (default 0) of the first database.
|
||||
own: Option<String>,
|
||||
/// `CP_PLAY`: a game against Maia at start (see `debug_screenshot`).
|
||||
play: Option<String>,
|
||||
keys: std::collections::VecDeque<(Modifiers, Key)>,
|
||||
next_key: f64,
|
||||
/// `CP_TYPE=<text>`: typed into the field that has the keyboard, 2.5 s after start.
|
||||
|
|
@ -261,6 +274,7 @@ impl DebugStartup {
|
|||
screenshot_requested: false,
|
||||
open_settings: false,
|
||||
own: std::env::var("CP_OWN").ok(),
|
||||
play: std::env::var("CP_PLAY").ok(),
|
||||
keys: std::env::var("CP_KEYS")
|
||||
.unwrap_or_default()
|
||||
.split_whitespace()
|
||||
|
|
@ -343,6 +357,8 @@ impl App {
|
|||
settings_ui: SettingsWindow::new(),
|
||||
toast: None,
|
||||
own: Own::default(),
|
||||
play_dialog: None,
|
||||
play_next: None,
|
||||
tx,
|
||||
rx,
|
||||
confirm_close: None,
|
||||
|
|
@ -432,6 +448,44 @@ impl App {
|
|||
self.debug.open_settings = false;
|
||||
self.settings_ui.open = true;
|
||||
}
|
||||
// `CP_PLAY=white|black[,5+3|none][,1500]`: a game against Maia starts at once;
|
||||
// `CP_PLAY=dialog`: the play dialog.
|
||||
if let Some(spec) = self.debug.play.take() {
|
||||
if spec == "dialog" {
|
||||
self.play_dialog = Some(crate::play::Dialog::new(&self.settings));
|
||||
} else {
|
||||
let mut parts = spec.split(',');
|
||||
let user = if parts.next() == Some("black") {
|
||||
chess_core::shakmaty::Color::Black
|
||||
} else {
|
||||
chess_core::shakmaty::Color::White
|
||||
};
|
||||
let clock = match parts.next() {
|
||||
Some("none") => None,
|
||||
Some(tc) => tc.split_once('+').and_then(|(m, i)| {
|
||||
Some(crate::play::TimeControl {
|
||||
base: m.parse::<u32>().ok()? * 60,
|
||||
increment: i.parse().ok()?,
|
||||
})
|
||||
}),
|
||||
None => Some(crate::play::TimeControl {
|
||||
base: 300,
|
||||
increment: 3,
|
||||
}),
|
||||
};
|
||||
let strength = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1500);
|
||||
self.start_play(
|
||||
ctx,
|
||||
crate::play::Start {
|
||||
user,
|
||||
strength,
|
||||
user_elo: self.settings.rating,
|
||||
user_name: self.settings.your_name.clone(),
|
||||
clock,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
if self.debug.own.is_some() && ctx.input(|i| i.time) > 1.5 {
|
||||
let what = self.debug.own.take().unwrap_or_default();
|
||||
// `CP_PASTE=<pgn text>`: this game is open first (a game from no database).
|
||||
|
|
@ -1230,6 +1284,18 @@ impl App {
|
|||
self.game = Some(GameView::new(g, None, Vec::new()));
|
||||
}
|
||||
|
||||
/// A new game against Maia (the weights are there: the dialog saw to it).
|
||||
fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) {
|
||||
let Some(weights) = crate::maia_download::installed() else {
|
||||
self.play_dialog = Some(crate::play::Dialog::new(&self.settings));
|
||||
return;
|
||||
};
|
||||
self.new_game();
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
g.start_play(start, weights, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The game's data for editing (F2, the title, the menu).
|
||||
fn edit_game_data(&mut self) {
|
||||
let Some(g) = &self.game else { return };
|
||||
|
|
@ -1682,9 +1748,11 @@ impl App {
|
|||
}
|
||||
|
||||
fn request_close(&mut self, ctx: &egui::Context, intent: CloseIntent) {
|
||||
// A comment being written goes into the game first.
|
||||
// A comment being written goes into the game first; a game against Maia still
|
||||
// being played ends (resigned, or dropped before the first moves).
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
g.commit_editor();
|
||||
g.resign_if_playing();
|
||||
}
|
||||
if self.game.as_ref().is_some_and(|g| g.game.is_modified()) {
|
||||
self.confirm_close = Some(intent);
|
||||
|
|
@ -1722,6 +1790,13 @@ impl App {
|
|||
{
|
||||
self.library.reveal(&src.path, src.index);
|
||||
}
|
||||
match self.play_next.take() {
|
||||
Some(PlayNext::Rematch(s)) => self.start_play(ctx, s),
|
||||
Some(PlayNext::Dialog) => {
|
||||
self.play_dialog = Some(crate::play::Dialog::new(&self.settings))
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some((path, start, line, flipped)) = self.find_after_close.take() {
|
||||
self.library.show_position(&path, start, line, flipped, ctx);
|
||||
}
|
||||
|
|
@ -1972,6 +2047,7 @@ impl App {
|
|||
Some(2) => {
|
||||
self.confirm_close = None;
|
||||
self.find_after_close = None;
|
||||
self.play_next = None;
|
||||
// A restart asked for waits for no later quit.
|
||||
self.restart_to = None;
|
||||
}
|
||||
|
|
@ -2003,6 +2079,7 @@ impl eframe::App for App {
|
|||
&& let Some(g) = self.game.as_mut()
|
||||
{
|
||||
g.commit_editor();
|
||||
g.resign_if_playing();
|
||||
}
|
||||
// Quitting with a modified game left for another (reference tab): show that one,
|
||||
// so the question "save?" is about the game that has the changes.
|
||||
|
|
@ -2054,6 +2131,9 @@ impl eframe::App for App {
|
|||
self.own.then_close = None;
|
||||
self.new_base_dialog(own_db::AfterCreate::Shelf);
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) && self.game.is_none() {
|
||||
self.play_dialog = Some(crate::play::Dialog::new(&self.settings));
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() {
|
||||
self.new_game();
|
||||
}
|
||||
|
|
@ -2134,6 +2214,34 @@ impl eframe::App for App {
|
|||
self.toast(&ctx, msg);
|
||||
}
|
||||
GameAction::Save => self.save_current(&ctx, None),
|
||||
GameAction::Rematch => {
|
||||
let next = self
|
||||
.game
|
||||
.as_ref()
|
||||
.and_then(|g| g.play_end.clone())
|
||||
.map(|e| {
|
||||
let mut s = e.start;
|
||||
s.user = match self.settings.play.color {
|
||||
crate::play::ColorChoice::Random => {
|
||||
if crate::play::random_unit() < 0.5 {
|
||||
chess_core::shakmaty::Color::White
|
||||
} else {
|
||||
chess_core::shakmaty::Color::Black
|
||||
}
|
||||
}
|
||||
_ => !s.user,
|
||||
};
|
||||
s
|
||||
});
|
||||
if let Some(s) = next {
|
||||
self.play_next = Some(PlayNext::Rematch(s));
|
||||
self.request_close(&ctx, CloseIntent::BackToLibrary);
|
||||
}
|
||||
}
|
||||
GameAction::PlayAgain => {
|
||||
self.play_next = Some(PlayNext::Dialog);
|
||||
self.request_close(&ctx, CloseIntent::BackToLibrary);
|
||||
}
|
||||
GameAction::AddToDatabase => {
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
g.commit_editor();
|
||||
|
|
@ -2202,6 +2310,9 @@ impl eframe::App for App {
|
|||
}
|
||||
LibraryAction::OpenPgn(text) => self.open_pgn_text(&ctx, text, true),
|
||||
LibraryAction::NewGame => self.new_game(),
|
||||
LibraryAction::Play => {
|
||||
self.play_dialog = Some(crate::play::Dialog::new(&self.settings))
|
||||
}
|
||||
LibraryAction::NewGameIn(path) => {
|
||||
self.new_game();
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
|
|
@ -2369,6 +2480,15 @@ impl eframe::App for App {
|
|||
|
||||
self.confirm_dialog(&ctx);
|
||||
self.own_dialogs(&ctx);
|
||||
if let Some(d) = self.play_dialog.as_mut()
|
||||
&& let Some(out) = d.show(&ctx, &mut self.settings)
|
||||
{
|
||||
self.play_dialog = None;
|
||||
if let crate::play::DialogOutcome::Play(start) = out {
|
||||
self.settings_dirty = true;
|
||||
self.start_play(&ctx, start);
|
||||
}
|
||||
}
|
||||
// Ctrl+Z on the library while the deleted game can still come back.
|
||||
if self.game.is_none()
|
||||
&& self.own.undo.is_some()
|
||||
|
|
|
|||
|
|
@ -62,6 +62,15 @@ pub struct GameView {
|
|||
scroll_to_cursor: bool,
|
||||
/// The comment being written (user-comments.md).
|
||||
editor: Option<CommentEditor>,
|
||||
/// A game against Maia in progress (play-mode.md).
|
||||
pub play: Option<crate::play::Session>,
|
||||
/// The game just played: the result strip.
|
||||
pub play_end: Option<crate::play::End>,
|
||||
/// What the play started with (for the end, a rematch).
|
||||
play_start: Option<crate::play::Start>,
|
||||
/// «The game is on» asked (leaving during a game); the clocks wait meanwhile.
|
||||
/// `true`: back to the previous game, not to the library.
|
||||
play_leave: Option<(bool, std::time::Instant)>,
|
||||
show_diagnostics: bool,
|
||||
engine_settings_open: bool,
|
||||
review: Review,
|
||||
|
|
@ -92,6 +101,10 @@ pub enum GameAction {
|
|||
CopyText(String, &'static str),
|
||||
/// Ctrl+S: into the game's own database, else "Add to database…".
|
||||
Save,
|
||||
/// After a game against Maia: the same again with colours swapped.
|
||||
Rematch,
|
||||
/// After a game against Maia: the play dialog.
|
||||
PlayAgain,
|
||||
/// Ctrl+Shift+S: choose the database to add the game to.
|
||||
AddToDatabase,
|
||||
/// F2: players, event, date, result…
|
||||
|
|
@ -138,6 +151,10 @@ impl GameView {
|
|||
preview: None,
|
||||
scroll_to_cursor: true,
|
||||
editor: None,
|
||||
play: None,
|
||||
play_end: None,
|
||||
play_start: None,
|
||||
play_leave: None,
|
||||
show_diagnostics: false,
|
||||
engine_settings_open: false,
|
||||
review,
|
||||
|
|
@ -241,6 +258,10 @@ impl GameView {
|
|||
/// A move made on the board or picked in the reference tab: goes to it if the
|
||||
/// game has it, else adds it (undoable).
|
||||
fn play_move(&mut self, m: Move, actions: &mut Vec<GameAction>) {
|
||||
if self.play.is_some() {
|
||||
self.user_move(m, actions);
|
||||
return;
|
||||
}
|
||||
match self.game.add_move(self.cursor, m) {
|
||||
Ok(id) => {
|
||||
self.goto(id);
|
||||
|
|
@ -601,7 +622,8 @@ impl GameView {
|
|||
{
|
||||
self.review.note_live_speed(analysis.nps, e.threads);
|
||||
}
|
||||
if input_enabled && !self.review.dialog_open {
|
||||
self.play_tick(ui.ctx(), &mut actions);
|
||||
if input_enabled && !self.review.dialog_open && self.play_leave.is_none() {
|
||||
self.editor_keys(ui, &mut actions);
|
||||
self.keyboard(ui, &mut actions);
|
||||
}
|
||||
|
|
@ -685,6 +707,10 @@ impl GameView {
|
|||
None => {}
|
||||
}
|
||||
|
||||
// Leaving during a game asks first; the question itself.
|
||||
self.guard_leaving(&mut actions);
|
||||
self.leave_question(ui.ctx(), &mut actions);
|
||||
|
||||
if self.show_diagnostics {
|
||||
let mut open = true;
|
||||
egui::Window::new(tr("PGN compatibility"))
|
||||
|
|
@ -1177,7 +1203,7 @@ impl GameView {
|
|||
} else {
|
||||
None
|
||||
},
|
||||
interactive: self.preview.is_none(),
|
||||
interactive: self.preview.is_none() && self.user_may_move(),
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
|
|
@ -1188,6 +1214,7 @@ impl GameView {
|
|||
}
|
||||
if let Some(drawn) = self.board.take_shape()
|
||||
&& self.preview.is_none()
|
||||
&& self.play.is_none()
|
||||
{
|
||||
self.apply_shape(drawn);
|
||||
}
|
||||
|
|
@ -1219,6 +1246,13 @@ impl GameView {
|
|||
hub: &mut crate::translate_ui::Hub,
|
||||
actions: &mut Vec<GameAction>,
|
||||
) {
|
||||
if self.play.is_some() {
|
||||
self.play_side(ui, settings, analysis, reference, hub, actions);
|
||||
return;
|
||||
}
|
||||
if self.play_end.is_some() {
|
||||
egui::Panel::top("play_result").show(ui, |ui| self.result_strip(ui, actions));
|
||||
}
|
||||
egui::Panel::bottom("game_toolbar").show(ui, |ui| self.toolbar(ui, actions));
|
||||
egui::Panel::top("engine_panel")
|
||||
.show(ui, |ui| self.engine_panel(ui, settings, analysis, actions));
|
||||
|
|
@ -1313,6 +1347,7 @@ impl GameView {
|
|||
.map(|p| (p.base, p.san.as_slice(), p.shown)),
|
||||
translations: self.translation.shown(),
|
||||
editor: self.editor.as_mut(),
|
||||
read_only: self.play.is_some(),
|
||||
}
|
||||
.show(ui);
|
||||
if let Some(id) = resp.clicked {
|
||||
|
|
@ -1895,6 +1930,718 @@ impl GameView {
|
|||
}
|
||||
}
|
||||
|
||||
// ----- playing against Maia (docs/design/play-mode.md) -----------------------------
|
||||
|
||||
/// Starts a game against Maia in this (new, empty) game.
|
||||
pub fn start_play(
|
||||
&mut self,
|
||||
start: crate::play::Start,
|
||||
weights: std::path::PathBuf,
|
||||
ctx: &egui::Context,
|
||||
) {
|
||||
use crate::play::{Clock, Opponent, Session};
|
||||
let maia = format!("Maia {}", start.strength);
|
||||
let you = if start.user_name.is_empty() {
|
||||
"?".to_owned()
|
||||
} else {
|
||||
start.user_name.clone()
|
||||
};
|
||||
let (white, black) = match start.user {
|
||||
Color::White => (you, maia),
|
||||
Color::Black => (maia, you),
|
||||
};
|
||||
let event = match start.clock {
|
||||
Some(tc) => trf(
|
||||
"Game vs computer, {speed}",
|
||||
&[("speed", &tc.speed().name().to_lowercase())],
|
||||
),
|
||||
None => tr("Game vs computer").to_owned(),
|
||||
};
|
||||
let g = &mut self.game;
|
||||
g.set_tag("Event", &event);
|
||||
g.set_tag("Site", "ChessPenguin");
|
||||
g.set_tag("White", &white);
|
||||
g.set_tag("Black", &black);
|
||||
let (we, be) = match start.user {
|
||||
Color::White => (start.user_elo, Some(start.strength)),
|
||||
Color::Black => (Some(start.strength), start.user_elo),
|
||||
};
|
||||
if let Some(e) = we {
|
||||
g.set_tag("WhiteElo", &e.to_string());
|
||||
}
|
||||
if let Some(e) = be {
|
||||
g.set_tag("BlackElo", &e.to_string());
|
||||
}
|
||||
let (wt, bt) = match start.user {
|
||||
Color::White => ("human", "program"),
|
||||
Color::Black => ("program", "human"),
|
||||
};
|
||||
g.set_tag("WhiteType", wt);
|
||||
g.set_tag("BlackType", bt);
|
||||
g.set_tag(
|
||||
"TimeControl",
|
||||
&start.clock.map_or_else(|| "-".to_owned(), |tc| tc.pgn()),
|
||||
);
|
||||
g.mark_saved();
|
||||
self.flipped = start.user == Color::Black;
|
||||
self.play_end = None;
|
||||
self.play = Some(Session {
|
||||
user: start.user,
|
||||
strength: start.strength,
|
||||
user_elo: start.user_elo,
|
||||
clock: start.clock.map(Clock::new),
|
||||
opponent: Opponent::start(weights, ctx),
|
||||
warned: false,
|
||||
resign_asked: false,
|
||||
});
|
||||
self.play_start = Some(start);
|
||||
self.ask_maia();
|
||||
}
|
||||
|
||||
/// The positions of the main line, from the start to its end.
|
||||
fn mainline_positions(&self) -> Vec<Chess> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(p) = self.game.position(NodeId::ROOT) {
|
||||
out.push(p.clone());
|
||||
}
|
||||
for id in self.game.mainline() {
|
||||
if let Some(p) = self.game.position(id) {
|
||||
out.push(p.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn play_end_node(&self) -> NodeId {
|
||||
self.game.line_end(NodeId::ROOT)
|
||||
}
|
||||
|
||||
/// The side to move at the end of the main line.
|
||||
fn play_turn(&self) -> Color {
|
||||
self.game
|
||||
.position(self.play_end_node())
|
||||
.map_or(Color::White, |p| p.turn())
|
||||
}
|
||||
|
||||
/// The user may move: their turn, at the current position, Maia not thinking.
|
||||
fn user_may_move(&self) -> bool {
|
||||
match &self.play {
|
||||
None => true,
|
||||
Some(s) => {
|
||||
self.play_leave.is_none()
|
||||
&& self.play_turn() == s.user
|
||||
&& self.cursor == self.play_end_node()
|
||||
&& !s.opponent.thinking
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks Maia for a move when it is her turn (dev hook `CP_PLAY_AUTO`: for the user
|
||||
/// too, quickly — a whole game without a mouse).
|
||||
fn ask_maia(&mut self) {
|
||||
let turn = self.play_turn();
|
||||
let positions = self.mainline_positions();
|
||||
let ply = positions.len() - 1;
|
||||
let only = positions.last().is_some_and(|p| p.legal_moves().len() == 1);
|
||||
let auto = std::env::var_os("CP_PLAY_AUTO").is_some();
|
||||
let Some(s) = self.play.as_mut() else { return };
|
||||
if turn == s.user {
|
||||
if auto {
|
||||
let elo = s.user_elo.unwrap_or(s.strength);
|
||||
s.opponent.ask(
|
||||
positions,
|
||||
elo,
|
||||
s.strength,
|
||||
std::time::Duration::from_millis(30),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
let clock = s
|
||||
.clock
|
||||
.as_ref()
|
||||
.map(|c| (c.left(turn, now), c.control.increment));
|
||||
let pause = if auto {
|
||||
std::time::Duration::from_millis(30)
|
||||
} else {
|
||||
crate::play::pause(clock, ply, only)
|
||||
};
|
||||
let oppo = s.user_elo.unwrap_or(s.strength);
|
||||
s.opponent.ask(positions, s.strength, oppo, pause);
|
||||
}
|
||||
|
||||
/// A move at the end of the main line by the side to move: the clock, `[%clk]`, the
|
||||
/// sound, the end of the game, Maia's turn.
|
||||
fn play_add(&mut self, m: Move, actions: &mut Vec<GameAction>) {
|
||||
let end = self.play_end_node();
|
||||
let mover = self.play_turn();
|
||||
let Ok(id) = self.game.add_move(end, m) else {
|
||||
return;
|
||||
};
|
||||
let now = std::time::Instant::now();
|
||||
if let Some(s) = self.play.as_mut() {
|
||||
s.resign_asked = false;
|
||||
if let Some(c) = s.clock.as_mut() {
|
||||
c.moved(mover, now);
|
||||
let left = c.left(mover, now);
|
||||
let _ = self
|
||||
.game
|
||||
.annotate(id, Vec::new(), vec![crate::play::clk_command(left)]);
|
||||
}
|
||||
}
|
||||
// The moves of a game played are not undone as edits (the take-back is).
|
||||
self.goto(id);
|
||||
if let Some(snd) = self.sound_for(id) {
|
||||
actions.push(GameAction::Sound(snd));
|
||||
}
|
||||
if let Some(e) = crate::play::ending(&self.mainline_positions()) {
|
||||
self.finish_play(e, actions);
|
||||
} else {
|
||||
self.ask_maia();
|
||||
}
|
||||
}
|
||||
|
||||
fn user_move(&mut self, m: Move, actions: &mut Vec<GameAction>) {
|
||||
if !self.user_may_move() {
|
||||
// A move in a past position: back to the game.
|
||||
let end = self.play_end_node();
|
||||
self.goto(end);
|
||||
return;
|
||||
}
|
||||
self.play_add(m, actions);
|
||||
}
|
||||
|
||||
/// The clock and Maia's answers, each frame.
|
||||
fn play_tick(&mut self, ctx: &egui::Context, actions: &mut Vec<GameAction>) {
|
||||
if self.play_leave.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(s) = self.play.as_mut() else { return };
|
||||
if let Some(err) = s.opponent.failed() {
|
||||
actions.push(GameAction::Toast(trf(
|
||||
"Maia did not start: {e}",
|
||||
&[("e", &err)],
|
||||
)));
|
||||
self.play = None;
|
||||
self.game.mark_saved();
|
||||
actions.push(GameAction::Back);
|
||||
return;
|
||||
}
|
||||
if let Some(m) = s.opponent.answer() {
|
||||
self.play_add(m, actions);
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
let end_pos = self.game.position(self.play_end_node()).cloned();
|
||||
let Some(s) = self.play.as_mut() else { return };
|
||||
if let Some(c) = &s.clock
|
||||
&& let Some(side) = c.running()
|
||||
{
|
||||
let left = c.left(side, now);
|
||||
if left.is_zero() {
|
||||
// Time is up; a draw when the other side cannot mate (FIDE 6.9).
|
||||
let draw = end_pos.is_some_and(|p| p.has_insufficient_material(!side));
|
||||
self.finish_play(crate::play::Ending::Time { loser: side, draw }, actions);
|
||||
return;
|
||||
}
|
||||
if side == s.user && left <= c.low() {
|
||||
s.warned = true;
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
/// The game is over: the result, the tags, the strip; the screen becomes an ordinary
|
||||
/// new game.
|
||||
fn finish_play(&mut self, ending: crate::play::Ending, actions: &mut Vec<GameAction>) {
|
||||
let Some(mut s) = self.play.take() else {
|
||||
return;
|
||||
};
|
||||
s.opponent.forget();
|
||||
let now = std::time::Instant::now();
|
||||
let left = s.clock.as_mut().map(|c| {
|
||||
c.stop(now);
|
||||
(c.left(s.user, now), c.left(!s.user, now))
|
||||
});
|
||||
self.game.set_result(ending.result());
|
||||
self.game.set_tag("Termination", ending.termination());
|
||||
let end = self.play_end_node();
|
||||
self.goto(end);
|
||||
if matches!(ending, crate::play::Ending::Checkmate { .. }) {
|
||||
actions.push(GameAction::Sound(Sound::Checkmate));
|
||||
}
|
||||
if let Some(start) = self.play_start.clone() {
|
||||
self.play_end = Some(crate::play::End {
|
||||
ending,
|
||||
user: s.user,
|
||||
start,
|
||||
left,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Before both sides have moved there is nothing to lose: the game is dropped.
|
||||
fn play_started(&self) -> bool {
|
||||
self.game.mainline().len() >= 2
|
||||
}
|
||||
|
||||
/// Resigns the game in progress (leaving it, closing the program); before the first
|
||||
/// moves it is dropped instead. The game stays as played.
|
||||
pub fn resign_if_playing(&mut self) {
|
||||
let Some(s) = &self.play else { return };
|
||||
if self.play_started() {
|
||||
let user = s.user;
|
||||
let mut sink = Vec::new();
|
||||
self.finish_play(crate::play::Ending::Resigned { loser: user }, &mut sink);
|
||||
} else {
|
||||
self.play = None;
|
||||
self.game.mark_saved();
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes back the user's last move and Maia's answer to it (no variation is left).
|
||||
fn take_back(&mut self) {
|
||||
let Some(s) = self.play.as_mut() else { return };
|
||||
s.opponent.forget();
|
||||
let user = s.user;
|
||||
// The last move of the user on the main line.
|
||||
let line = self.game.mainline();
|
||||
let last = line.iter().rev().find(|&&id| {
|
||||
self.game
|
||||
.parent(id)
|
||||
.and_then(|p| self.game.position(p))
|
||||
.is_some_and(|p| p.turn() == user)
|
||||
});
|
||||
if let Some(&id) = last
|
||||
&& let Ok(parent) = self.game.delete_variation(id)
|
||||
{
|
||||
self.goto(parent);
|
||||
}
|
||||
self.ask_maia();
|
||||
}
|
||||
|
||||
/// Keys during a game: looking through it, flipping, the take-back; Esc asks.
|
||||
fn play_keys(&mut self, ui: &Ui, actions: &mut Vec<GameAction>) {
|
||||
let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);
|
||||
let mut cmds = Vec::new();
|
||||
ui.input_mut(|i| {
|
||||
if i.consume_shortcut(&ctrl(Key::Z)) {
|
||||
cmds.push("takeback");
|
||||
}
|
||||
if i.consume_shortcut(&ctrl(Key::W)) {
|
||||
cmds.push("leave");
|
||||
}
|
||||
if i.modifiers.is_none() {
|
||||
for (key, cmd) in [
|
||||
(Key::ArrowLeft, "back1"),
|
||||
(Key::ArrowRight, "fwd1"),
|
||||
(Key::ArrowUp, "end"),
|
||||
(Key::ArrowDown, "home"),
|
||||
(Key::Home, "home"),
|
||||
(Key::End, "end"),
|
||||
(Key::F, "flip"),
|
||||
(Key::L, "engine"),
|
||||
(Key::Escape, "leave"),
|
||||
] {
|
||||
if i.key_pressed(key) {
|
||||
cmds.push(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) {
|
||||
cmds.push("engine");
|
||||
}
|
||||
});
|
||||
for cmd in cmds {
|
||||
match cmd {
|
||||
"takeback" => self.take_back(),
|
||||
"back1" => self.step_back(),
|
||||
"fwd1" => self.step_forward(actions),
|
||||
"home" => self.goto(NodeId::ROOT),
|
||||
"end" => {
|
||||
let end = self.play_end_node();
|
||||
self.goto(end);
|
||||
}
|
||||
"flip" => self.flipped = !self.flipped,
|
||||
"engine" => actions.push(GameAction::Toast(
|
||||
tr("The engine is off during the game — analyse after it ends").to_owned(),
|
||||
)),
|
||||
"leave" => {
|
||||
if let Some(s) = self.play.as_mut()
|
||||
&& s.resign_asked
|
||||
{
|
||||
s.resign_asked = false;
|
||||
} else {
|
||||
ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
|
||||
actions.push(GameAction::Back);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaving during a game asks first (play-mode.md §6); before the first moves of
|
||||
/// both sides the game is just dropped.
|
||||
fn guard_leaving(&mut self, actions: &mut Vec<GameAction>) {
|
||||
if self.play.is_none() {
|
||||
return;
|
||||
}
|
||||
let leaving = actions
|
||||
.iter()
|
||||
.position(|a| matches!(a, GameAction::Back | GameAction::ReturnToPrevious));
|
||||
if let Some(k) = leaving {
|
||||
let a = actions.remove(k);
|
||||
if self.play_started() {
|
||||
let previous = matches!(a, GameAction::ReturnToPrevious);
|
||||
self.play_leave = Some((previous, std::time::Instant::now()));
|
||||
} else {
|
||||
if let Some(s) = self.play.as_mut() {
|
||||
s.opponent.forget();
|
||||
}
|
||||
self.play = None;
|
||||
self.game.mark_saved();
|
||||
actions.push(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// «The game is on»: resign and add, resign and leave, keep playing.
|
||||
fn leave_question(&mut self, ctx: &egui::Context, actions: &mut Vec<GameAction>) {
|
||||
let Some((previous, since)) = self.play_leave else {
|
||||
return;
|
||||
};
|
||||
let action = if previous {
|
||||
GameAction::ReturnToPrevious
|
||||
} else {
|
||||
GameAction::Back
|
||||
};
|
||||
let mut choice = None;
|
||||
egui::Modal::new(egui::Id::new("play_leave")).show(ctx, |ui| {
|
||||
ui.set_width(460.0);
|
||||
ui.heading(tr("The game is on"));
|
||||
ui.label(tr("If you leave, the game ends with your resignation."));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button(tr("Resign and add to a database…")).clicked() {
|
||||
choice = Some(0);
|
||||
}
|
||||
if ui.button(tr("Resign and leave")).clicked() {
|
||||
choice = Some(1);
|
||||
}
|
||||
if crate::widgets::primary(ui, tr("Keep playing")).clicked() {
|
||||
choice = Some(2);
|
||||
}
|
||||
});
|
||||
});
|
||||
if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
|
||||
choice = Some(2);
|
||||
}
|
||||
let Some(choice) = choice else { return };
|
||||
self.play_leave = None;
|
||||
// The clocks waited while the question was open.
|
||||
let waited = since.elapsed();
|
||||
if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) {
|
||||
c.pause(waited);
|
||||
}
|
||||
match choice {
|
||||
0 => {
|
||||
self.resign_if_playing();
|
||||
actions.push(GameAction::Save);
|
||||
}
|
||||
1 => {
|
||||
self.resign_if_playing();
|
||||
actions.push(action);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The side panel during a game: the opponent's clock, the notation, the user's
|
||||
/// clock, the game's buttons.
|
||||
fn play_side(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
settings: &mut Settings,
|
||||
analysis: &mut Analysis,
|
||||
reference: &mut crate::reference::Reference,
|
||||
hub: &mut crate::translate_ui::Hub,
|
||||
actions: &mut Vec<GameAction>,
|
||||
) {
|
||||
let _ = (settings, analysis, reference, hub);
|
||||
let Some(s) = &self.play else { return };
|
||||
let user = s.user;
|
||||
// The side whose pieces are at the top of the board is at the top.
|
||||
let top = if self.flipped {
|
||||
Color::White
|
||||
} else {
|
||||
Color::Black
|
||||
};
|
||||
egui::Panel::bottom("play_toolbar").show(ui, |ui| self.play_toolbar(ui, actions));
|
||||
egui::Panel::bottom("play_card_bottom")
|
||||
.show_separator_line(false)
|
||||
.show(ui, |ui| self.clock_card(ui, !top, user));
|
||||
egui::Panel::top("play_card_top")
|
||||
.show_separator_line(false)
|
||||
.show(ui, |ui| self.clock_card(ui, top, user));
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
let resp = Notation {
|
||||
game: &self.game,
|
||||
cursor: self.cursor,
|
||||
scroll_to_cursor: self.scroll_to_cursor,
|
||||
marks: None,
|
||||
preview: None,
|
||||
translations: None,
|
||||
editor: None,
|
||||
read_only: true,
|
||||
}
|
||||
.show(ui);
|
||||
if let Some(id) = resp.clicked {
|
||||
self.goto(id);
|
||||
}
|
||||
self.scroll_to_cursor = false;
|
||||
});
|
||||
if self.cursor != self.play_end_node()
|
||||
&& ui
|
||||
.link(
|
||||
RichText::new(tr("Viewing an earlier position · back to the game — End"))
|
||||
.weak(),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
let end = self.play_end_node();
|
||||
self.goto(end);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A player's card: name, rating, the clock and what is going on.
|
||||
fn clock_card(&self, ui: &mut Ui, side: Color, user: Color) {
|
||||
let Some(s) = &self.play else { return };
|
||||
let now = std::time::Instant::now();
|
||||
let turn = self.play_turn();
|
||||
let active = turn == side;
|
||||
let left = s.clock.as_ref().map(|c| c.left(side, now));
|
||||
let low = s
|
||||
.clock
|
||||
.as_ref()
|
||||
.zip(left)
|
||||
.is_some_and(|(c, l)| c.running() == Some(side) && l <= c.low());
|
||||
let sel = ui.visuals().selection;
|
||||
let mut frame = egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(10, 6))
|
||||
.corner_radius(4)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
ui.visuals().widgets.noninteractive.bg_stroke.color,
|
||||
));
|
||||
if active {
|
||||
frame = frame.fill(sel.bg_fill.gamma_multiply(0.35));
|
||||
}
|
||||
if low {
|
||||
frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
frame.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
let king = if side == Color::White { "♔" } else { "♚" };
|
||||
let name = if side == user {
|
||||
match s.user_elo {
|
||||
Some(r) => format!("{king} {} · {r}", tr("You")),
|
||||
None => format!("{king} {}", tr("You")),
|
||||
}
|
||||
} else {
|
||||
format!("{king} Maia {}", s.strength)
|
||||
};
|
||||
ui.label(RichText::new(name).size(15.0));
|
||||
let state = if side != user && s.opponent.thinking {
|
||||
tr("thinking…")
|
||||
} else if side == user && active {
|
||||
tr("your move")
|
||||
} else if side != user {
|
||||
tr("waiting")
|
||||
} else {
|
||||
""
|
||||
};
|
||||
ui.label(RichText::new(state).weak().size(13.0));
|
||||
});
|
||||
if let Some(left) = left {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let mut t = RichText::new(crate::play::clock_text(left))
|
||||
.monospace()
|
||||
.size(28.0);
|
||||
if low {
|
||||
t = t.color(ui.visuals().error_fg_color);
|
||||
} else if active {
|
||||
t = t.strong();
|
||||
} else {
|
||||
t = t.weak();
|
||||
}
|
||||
ui.label(t);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
/// ⏮ ◀ ▶ ⏭ · 🔃 · ↶ Take back · 🏳 Resign (✕ Abort before the first moves).
|
||||
fn play_toolbar(&mut self, ui: &mut Ui, actions: &mut Vec<GameAction>) {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let big = |s: &str| RichText::new(s).size(18.0);
|
||||
if ui.button(big("⏮")).clicked() {
|
||||
self.goto(NodeId::ROOT);
|
||||
}
|
||||
if ui.button(big("◀")).clicked() {
|
||||
self.step_back();
|
||||
}
|
||||
if ui.button(big("▶")).clicked() {
|
||||
self.step_forward(actions);
|
||||
}
|
||||
if ui.button(big("⏭")).clicked() {
|
||||
let end = self.play_end_node();
|
||||
self.goto(end);
|
||||
}
|
||||
ui.separator();
|
||||
if ui
|
||||
.button(big("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.flipped = !self.flipped;
|
||||
}
|
||||
ui.separator();
|
||||
let user = self.play.as_ref().map_or(Color::White, |s| s.user);
|
||||
let user_moved = self.game.mainline().iter().any(|&id| {
|
||||
self.game
|
||||
.parent(id)
|
||||
.and_then(|p| self.game.position(p))
|
||||
.is_some_and(|p| p.turn() == user)
|
||||
});
|
||||
if ui
|
||||
.add_enabled(user_moved, egui::Button::new(tr("↶ Take back")))
|
||||
.on_hover_text(tr("Take back a move (Ctrl+Z)"))
|
||||
.clicked()
|
||||
{
|
||||
self.take_back();
|
||||
}
|
||||
if !self.play_started() {
|
||||
if ui
|
||||
.button(tr("× Abort"))
|
||||
.on_hover_text(tr("Leave without a result: no moves made yet"))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(GameAction::Back);
|
||||
}
|
||||
} else if self.play.as_ref().is_some_and(|s| s.resign_asked) {
|
||||
ui.label(tr("Resign?"));
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(RichText::new(tr("Yes")).color(Color32::WHITE))
|
||||
.fill(ui.visuals().error_fg_color),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
let user = self.play.as_ref().map_or(Color::White, |s| s.user);
|
||||
self.finish_play(crate::play::Ending::Resigned { loser: user }, actions);
|
||||
} else if ui.button(tr("No")).clicked()
|
||||
&& let Some(s) = self.play.as_mut()
|
||||
{
|
||||
s.resign_asked = false;
|
||||
}
|
||||
} else if ui.button(tr("⚑ Resign")).clicked()
|
||||
&& let Some(s) = self.play.as_mut()
|
||||
{
|
||||
s.resign_asked = true;
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
/// The strip above the notation after a game: the result and what to do next.
|
||||
fn result_strip(&mut self, ui: &mut Ui, actions: &mut Vec<GameAction>) {
|
||||
let Some(end) = self.play_end.clone() else {
|
||||
return;
|
||||
};
|
||||
let mut close = false;
|
||||
ui.add_space(4.0);
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(10, 8))
|
||||
.corner_radius(4)
|
||||
.fill(ui.visuals().extreme_bg_color)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
ui.visuals().widgets.noninteractive.bg_stroke.color,
|
||||
))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(
|
||||
RichText::new(format!(" {} ", end.ending.result().as_str()))
|
||||
.strong()
|
||||
.size(15.0)
|
||||
.background_color(ui.visuals().widgets.inactive.weak_bg_fill),
|
||||
);
|
||||
ui.label(RichText::new(end.heading()).strong().size(17.0));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::widgets::small_close_button(ui)
|
||||
.on_hover_text(tr("Close"))
|
||||
.clicked()
|
||||
{
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
if !end.detail().is_empty() {
|
||||
ui.label(end.detail());
|
||||
}
|
||||
if let Some((you, maia)) = end.left {
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"Left: you {you} · Maia {maia}",
|
||||
&[
|
||||
("you", &crate::play::clock_text(you)),
|
||||
("maia", &crate::play::clock_text(maia)),
|
||||
],
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if crate::widgets::primary(ui, tr("📈 Analyse")).clicked() {
|
||||
self.review.dialog_open = true;
|
||||
}
|
||||
if ui
|
||||
.button(tr("↻ Rematch"))
|
||||
.on_hover_text(tr("Same settings, colours swapped"))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(GameAction::Rematch);
|
||||
}
|
||||
if ui.button(tr("⚔ New game")).clicked() {
|
||||
actions.push(GameAction::PlayAgain);
|
||||
}
|
||||
if ui
|
||||
.button(tr("💾 Save to a database…"))
|
||||
.on_hover_text("Ctrl+S")
|
||||
.clicked()
|
||||
{
|
||||
actions.push(GameAction::Save);
|
||||
}
|
||||
});
|
||||
});
|
||||
if close {
|
||||
self.play_end = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Dev hook (`CP_SHAPE=Ge2e4,Rd5`): shapes drawn on the board at the current move.
|
||||
pub fn debug_shapes(&mut self, spec: &str) {
|
||||
for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
|
||||
|
|
@ -1983,6 +2730,10 @@ impl GameView {
|
|||
if ui.ctx().egui_wants_keyboard_input() {
|
||||
return;
|
||||
}
|
||||
if self.play.is_some() {
|
||||
self.play_keys(ui, actions);
|
||||
return;
|
||||
}
|
||||
let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);
|
||||
let ctrl_shift = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k);
|
||||
let overlay = crate::app::overlay_open(ui.ctx());
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ pub enum LibraryAction {
|
|||
/// Open PGN text as a new game.
|
||||
OpenPgn(String),
|
||||
NewGame,
|
||||
/// A game against Maia: the play dialog.
|
||||
Play,
|
||||
/// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there.
|
||||
NewGameIn(PathBuf),
|
||||
PastePgn,
|
||||
|
|
@ -116,10 +118,15 @@ fn legacy_pgn(path: &Path) -> bool {
|
|||
/// `Library::app_buttons`), with the gap that sets the game ones apart from the
|
||||
/// database actions.
|
||||
fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 {
|
||||
let texts: [&str; 3] = if icons {
|
||||
["⚙", "📋", "♟"]
|
||||
let texts: [&str; 4] = if icons {
|
||||
["⚙", "📋", "♟", "⚔"]
|
||||
} else {
|
||||
[tr("⚙ Settings"), tr("📋 Paste PGN"), tr("♟ New game")]
|
||||
[
|
||||
tr("⚙ Settings"),
|
||||
tr("📋 Paste PGN"),
|
||||
tr("♟ New game"),
|
||||
tr("⚔ Play"),
|
||||
]
|
||||
};
|
||||
texts.iter().map(|t| button_w(ui, t)).sum::<f32>()
|
||||
+ update.map_or(0.0, |v| button_w(ui, v))
|
||||
|
|
@ -705,6 +712,16 @@ impl Library {
|
|||
{
|
||||
actions.push(LibraryAction::NewGame);
|
||||
}
|
||||
if ui
|
||||
.button(label(tr("⚔ Play"), "⚔"))
|
||||
.on_hover_text(hint(
|
||||
tr("⚔ Play"),
|
||||
tr("A game against Maia, which plays like a human of the chosen rating (Ctrl+G)"),
|
||||
))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::Play);
|
||||
}
|
||||
if ui
|
||||
.button(label(tr("📋 Paste PGN"), "📋"))
|
||||
.on_hover_text(hint(
|
||||
|
|
|
|||
128
apps/desktop/src/maia_download.rs
Normal file
128
apps/desktop/src/maia_download.rs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
//! Downloading the Maia-3 weights on request: the published checkpoint `maia3-5m.pt`
|
||||
//! of a pinned revision from huggingface.co/UofTCSSLab/Maia3-5M, checked against its
|
||||
//! SHA-256 and loaded once before use. Nothing is downloaded without the user asking;
|
||||
//! the file is the authors' own, not redistributed by us.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const REVISION: &str = "b6559de2398d7140b985f28fd2c19fb5e47ddabe";
|
||||
const FILE: &str = "maia3-5m.pt";
|
||||
const SHA256: &str = "ba14208b2992d85502f5fb501934abf6aaaeb355e9f3fdf90e326911f562524f";
|
||||
pub const SIZE: u64 = 20_968_049;
|
||||
|
||||
/// `<local data dir>/maia/maia3-5m.pt`.
|
||||
fn dir() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
|
||||
.map(|d| d.data_local_dir().join("maia"))
|
||||
}
|
||||
|
||||
/// The weights, when they are there (`CP_MAIA` points elsewhere: development).
|
||||
pub fn installed() -> Option<PathBuf> {
|
||||
if let Some(p) = std::env::var_os("CP_MAIA") {
|
||||
return Some(PathBuf::from(p));
|
||||
}
|
||||
let p = dir()?.join(FILE);
|
||||
p.is_file().then_some(p)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Stage {
|
||||
Downloading { done: u64 },
|
||||
Checking,
|
||||
Done(PathBuf),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// A download in a background thread.
|
||||
pub struct Download {
|
||||
stage: Arc<Mutex<Stage>>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Download {
|
||||
pub fn start(ctx: &egui::Context) -> Download {
|
||||
let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0 }));
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone());
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("maia-download".into())
|
||||
.spawn(move || {
|
||||
let report = |st: Stage| {
|
||||
if let Ok(mut g) = s.lock() {
|
||||
*g = st;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
};
|
||||
let end = match run(&report, &c) {
|
||||
Ok(p) => Stage::Done(p),
|
||||
Err(e) => Stage::Failed(e),
|
||||
};
|
||||
report(end);
|
||||
});
|
||||
Download { stage, cancel }
|
||||
}
|
||||
|
||||
pub fn stage(&self) -> Stage {
|
||||
self.stage
|
||||
.lock()
|
||||
.map(|g| g.clone())
|
||||
.unwrap_or(Stage::Failed(String::new()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Download {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result<PathBuf, String> {
|
||||
let dir = dir().ok_or("no data directory")?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let part = dir.join(format!("{FILE}.part"));
|
||||
let url = format!("https://huggingface.co/UofTCSSLab/Maia3-5M/resolve/{REVISION}/{FILE}");
|
||||
let result = (|| {
|
||||
let mut response = ureq::get(&url).call().map_err(|e| e.to_string())?;
|
||||
let mut body = response.body_mut().with_config().limit(SIZE + 1).reader();
|
||||
let mut file = std::fs::File::create(&part).map_err(|e| e.to_string())?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = vec![0u8; 256 * 1024];
|
||||
let mut done = 0u64;
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err("cancelled".to_owned());
|
||||
}
|
||||
let n = body.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buf[..n]);
|
||||
file.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||
done += n as u64;
|
||||
report(Stage::Downloading { done });
|
||||
}
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
let digest: String = hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
if done != SIZE || digest != SHA256 {
|
||||
return Err(crate::i18n::tr("The file is not the published one").to_owned());
|
||||
}
|
||||
report(Stage::Checking);
|
||||
maia::Maia::load(&part).map_err(|e| e.to_string())?;
|
||||
let dest = dir.join(FILE);
|
||||
std::fs::rename(&part, &dest).map_err(|e| e.to_string())?;
|
||||
Ok(dest)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
|
@ -16,10 +16,12 @@ mod graphics;
|
|||
mod i18n;
|
||||
mod large_db;
|
||||
mod library;
|
||||
mod maia_download;
|
||||
mod notation;
|
||||
mod online;
|
||||
mod online_ui;
|
||||
mod own_db;
|
||||
mod play;
|
||||
mod reference;
|
||||
mod review;
|
||||
mod san;
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ pub struct Notation<'a> {
|
|||
pub translations: Option<&'a HashMap<String, Translated>>,
|
||||
/// The comment being written, drawn where the comment stands (user-comments.md §3).
|
||||
pub editor: Option<&'a mut CommentEditor>,
|
||||
/// A game being played: moves only show their position (no menus, no editing).
|
||||
pub read_only: bool,
|
||||
}
|
||||
|
||||
/// Result of a frame of the notation panel.
|
||||
|
|
@ -328,6 +330,9 @@ fn handle_move_response(
|
|||
resp.scroll_to_me(Some(egui::Align::Center));
|
||||
}
|
||||
let is_variation = n.game.child_index(id).is_some_and(|i| i > 0) || !n.game.is_mainline(id);
|
||||
if n.read_only {
|
||||
return;
|
||||
}
|
||||
// The menu is about the move it opens on: the move becomes the current one.
|
||||
if resp.secondary_clicked() && id != n.cursor {
|
||||
out.clicked = Some(id);
|
||||
|
|
|
|||
962
apps/desktop/src/play.rs
Normal file
962
apps/desktop/src/play.rs
Normal file
|
|
@ -0,0 +1,962 @@
|
|||
//! Playing against Maia (docs/research/play-mode.md, docs/design/play-mode.md): time
|
||||
//! controls as on Lichess, the clock, the end of a game, and Maia's moves computed in a
|
||||
//! background thread with a human-like pause.
|
||||
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use chess_core::shakmaty::zobrist::Zobrist64;
|
||||
use chess_core::shakmaty::{Chess, Color, EnPassantMode, Move, Position};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
// ----- time controls --------------------------------------------------------------------
|
||||
|
||||
/// A clock: base seconds and increment seconds; `None` in the settings is "no clock".
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TimeControl {
|
||||
pub base: u32,
|
||||
pub increment: u32,
|
||||
}
|
||||
|
||||
/// The pools of Lichess (lila `PoolList.scala`).
|
||||
pub const PRESETS: [TimeControl; 11] = [
|
||||
TimeControl {
|
||||
base: 60,
|
||||
increment: 0,
|
||||
},
|
||||
TimeControl {
|
||||
base: 120,
|
||||
increment: 1,
|
||||
},
|
||||
TimeControl {
|
||||
base: 180,
|
||||
increment: 0,
|
||||
},
|
||||
TimeControl {
|
||||
base: 180,
|
||||
increment: 2,
|
||||
},
|
||||
TimeControl {
|
||||
base: 300,
|
||||
increment: 0,
|
||||
},
|
||||
TimeControl {
|
||||
base: 300,
|
||||
increment: 3,
|
||||
},
|
||||
TimeControl {
|
||||
base: 600,
|
||||
increment: 0,
|
||||
},
|
||||
TimeControl {
|
||||
base: 600,
|
||||
increment: 5,
|
||||
},
|
||||
TimeControl {
|
||||
base: 900,
|
||||
increment: 10,
|
||||
},
|
||||
TimeControl {
|
||||
base: 1800,
|
||||
increment: 0,
|
||||
},
|
||||
TimeControl {
|
||||
base: 1800,
|
||||
increment: 20,
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Speed {
|
||||
UltraBullet,
|
||||
Bullet,
|
||||
Blitz,
|
||||
Rapid,
|
||||
Classical,
|
||||
}
|
||||
|
||||
impl Speed {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Speed::UltraBullet => tr("UltraBullet"),
|
||||
Speed::Bullet => tr("Bullet"),
|
||||
Speed::Blitz => tr("Blitz"),
|
||||
Speed::Rapid => tr("Rapid"),
|
||||
Speed::Classical => tr("Classical"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeControl {
|
||||
/// The category by the estimated length, base + 40 × increment (scalachess
|
||||
/// `Speed.scala`).
|
||||
pub fn speed(self) -> Speed {
|
||||
match self.base + 40 * self.increment {
|
||||
0..30 => Speed::UltraBullet,
|
||||
30..180 => Speed::Bullet,
|
||||
180..480 => Speed::Blitz,
|
||||
480..1500 => Speed::Rapid,
|
||||
_ => Speed::Classical,
|
||||
}
|
||||
}
|
||||
|
||||
/// «5+3», «½+0» as Lichess writes it (minutes + seconds).
|
||||
pub fn label(self) -> String {
|
||||
let min = match self.base {
|
||||
15 => "¼".to_owned(),
|
||||
30 => "½".to_owned(),
|
||||
45 => "¾".to_owned(),
|
||||
90 => "1½".to_owned(),
|
||||
b => (b / 60).to_string(),
|
||||
};
|
||||
format!("{min}+{}", self.increment)
|
||||
}
|
||||
|
||||
/// The PGN tag `TimeControl`: seconds + increment.
|
||||
pub fn pgn(self) -> String {
|
||||
format!("{}+{}", self.base, self.increment)
|
||||
}
|
||||
}
|
||||
|
||||
/// The minutes the custom control offers (Lichess `timeControl.ts`), in seconds.
|
||||
pub const CUSTOM_BASES: &[u32] = &[
|
||||
0, 15, 30, 45, 60, 90, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900,
|
||||
960, 1020, 1080, 1140, 1200, 1500, 1800, 2100, 2400, 2700, 3600, 4500, 5400, 6300, 7200, 8100,
|
||||
9000, 9900, 10800,
|
||||
];
|
||||
pub const CUSTOM_INCREMENTS: &[u32] = &[
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 35, 40, 45,
|
||||
60, 90, 120, 150, 180,
|
||||
];
|
||||
|
||||
/// The colour the user asks for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ColorChoice {
|
||||
White,
|
||||
#[default]
|
||||
Random,
|
||||
Black,
|
||||
}
|
||||
|
||||
/// The last choices of the play dialog (settings).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct PlayPrefs {
|
||||
pub color: ColorChoice,
|
||||
/// `None`: no clock.
|
||||
pub clock: Option<TimeControl>,
|
||||
/// Maia's rating, 600–2600.
|
||||
pub strength: u32,
|
||||
}
|
||||
|
||||
impl Default for PlayPrefs {
|
||||
fn default() -> Self {
|
||||
PlayPrefs {
|
||||
color: ColorChoice::Random,
|
||||
clock: Some(TimeControl {
|
||||
base: 300,
|
||||
increment: 3,
|
||||
}),
|
||||
strength: 1500,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const STRENGTH_MIN: u32 = 600;
|
||||
pub const STRENGTH_MAX: u32 = 2600;
|
||||
|
||||
/// «As me»: the user's rating rounded to 100, within Maia's range.
|
||||
pub fn strength_like(rating: u32) -> u32 {
|
||||
(((rating + 50) / 100) * 100).clamp(STRENGTH_MIN, STRENGTH_MAX)
|
||||
}
|
||||
|
||||
// ----- the clock -----------------------------------------------------------------------
|
||||
|
||||
/// Both clocks. Time runs for the side to move from the moment its opponent moved; a
|
||||
/// side's first move takes no time (Lichess); the increment comes after the move.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Clock {
|
||||
pub control: TimeControl,
|
||||
left: [Duration; 2],
|
||||
moved: [bool; 2],
|
||||
running: Option<(Color, Instant)>,
|
||||
}
|
||||
|
||||
fn idx(c: Color) -> usize {
|
||||
match c {
|
||||
Color::White => 0,
|
||||
Color::Black => 1,
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
pub fn new(control: TimeControl) -> Clock {
|
||||
// A base of 0 starts from the increment, at least 3 s (scalachess).
|
||||
let start = if control.base == 0 {
|
||||
Duration::from_secs(u64::from(control.increment.max(3)))
|
||||
} else {
|
||||
Duration::from_secs(u64::from(control.base))
|
||||
};
|
||||
Clock {
|
||||
control,
|
||||
left: [start; 2],
|
||||
moved: [false; 2],
|
||||
running: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The time left of `c` at `now`.
|
||||
pub fn left(&self, c: Color, now: Instant) -> Duration {
|
||||
let base = self.left[idx(c)];
|
||||
match self.running {
|
||||
Some((r, since)) if r == c && self.moved[idx(c)] => base.saturating_sub(now - since),
|
||||
_ => base,
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` has moved: its time is taken (not on its first move), the increment added,
|
||||
/// the other side's clock starts.
|
||||
pub fn moved(&mut self, c: Color, now: Instant) {
|
||||
let i = idx(c);
|
||||
if self.moved[i] {
|
||||
self.left[i] = self.left(c, now);
|
||||
}
|
||||
self.moved[i] = true;
|
||||
self.left[i] += Duration::from_secs(u64::from(self.control.increment));
|
||||
self.running = Some((!c, now));
|
||||
}
|
||||
|
||||
/// The side to move, its clock running (after its first move).
|
||||
pub fn running(&self) -> Option<Color> {
|
||||
self.running.map(|(c, _)| c).filter(|c| self.moved[idx(*c)])
|
||||
}
|
||||
|
||||
/// The clocks waited (a question about leaving was open): the running one is moved
|
||||
/// on by `d`, as if no time passed.
|
||||
pub fn pause(&mut self, d: Duration) {
|
||||
if let Some((_, since)) = self.running.as_mut() {
|
||||
*since += d;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop(&mut self, now: Instant) {
|
||||
if let Some((c, _)) = self.running {
|
||||
self.left[idx(c)] = self.left(c, now);
|
||||
}
|
||||
self.running = None;
|
||||
}
|
||||
|
||||
/// The low-time threshold: min(60, max(10, base / 8)) seconds (scalachess).
|
||||
pub fn low(&self) -> Duration {
|
||||
Duration::from_secs(u64::from((self.control.base / 8).clamp(10, 60)))
|
||||
}
|
||||
}
|
||||
|
||||
/// «4:58», «1:02:03», «0:09.4» (tenths under 10 s).
|
||||
pub fn clock_text(d: Duration) -> String {
|
||||
let ms = d.as_millis();
|
||||
let s = ms / 1000;
|
||||
if s >= 3600 {
|
||||
format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
|
||||
} else if ms < 10_000 {
|
||||
format!("0:{:02}.{}", s, ms / 100 % 10)
|
||||
} else {
|
||||
format!("{}:{:02}", s / 60, s % 60)
|
||||
}
|
||||
}
|
||||
|
||||
/// `[%clk 0:04:58]` for the PGN.
|
||||
pub fn clk_command(d: Duration) -> String {
|
||||
let s = d.as_secs();
|
||||
format!("[%clk {}:{:02}:{:02}]", s / 3600, s / 60 % 60, s % 60)
|
||||
}
|
||||
|
||||
// ----- the end of a game ---------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Ending {
|
||||
Checkmate {
|
||||
winner: Color,
|
||||
},
|
||||
Stalemate,
|
||||
InsufficientMaterial,
|
||||
Threefold,
|
||||
FiftyMoves,
|
||||
/// `loser` ran out of time; a draw when the other side cannot mate.
|
||||
Time {
|
||||
loser: Color,
|
||||
draw: bool,
|
||||
},
|
||||
Resigned {
|
||||
loser: Color,
|
||||
},
|
||||
}
|
||||
|
||||
impl Ending {
|
||||
pub fn result(self) -> chess_core::GameResult {
|
||||
use chess_core::GameResult as R;
|
||||
let win = |c: Color| match c {
|
||||
Color::White => R::WhiteWins,
|
||||
Color::Black => R::BlackWins,
|
||||
};
|
||||
match self {
|
||||
Ending::Checkmate { winner } => win(winner),
|
||||
Ending::Time { draw: true, .. } => R::Draw,
|
||||
Ending::Time { loser, .. } | Ending::Resigned { loser } => win(!loser),
|
||||
Ending::Stalemate
|
||||
| Ending::InsufficientMaterial
|
||||
| Ending::Threefold
|
||||
| Ending::FiftyMoves => R::Draw,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tag `Termination` (as Lichess writes it).
|
||||
pub fn termination(self) -> &'static str {
|
||||
match self {
|
||||
Ending::Time { .. } => "Time forfeit",
|
||||
_ => "Normal",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the game stands after the last of `positions` (the positions of the main line
|
||||
/// from the start): mate, stalemate, no material, threefold repetition, fifty moves.
|
||||
pub fn ending(positions: &[Chess]) -> Option<Ending> {
|
||||
let pos = positions.last()?;
|
||||
if pos.is_checkmate() {
|
||||
return Some(Ending::Checkmate {
|
||||
winner: !pos.turn(),
|
||||
});
|
||||
}
|
||||
if pos.is_stalemate() {
|
||||
return Some(Ending::Stalemate);
|
||||
}
|
||||
if pos.is_insufficient_material() {
|
||||
return Some(Ending::InsufficientMaterial);
|
||||
}
|
||||
let key = |p: &Chess| p.zobrist_hash::<Zobrist64>(EnPassantMode::Legal);
|
||||
let now = key(pos);
|
||||
// Only positions since the last capture or pawn move can repeat.
|
||||
let span = (pos.halfmoves() as usize + 1).min(positions.len());
|
||||
let repeats = positions[positions.len() - span..]
|
||||
.iter()
|
||||
.filter(|p| key(p) == now)
|
||||
.count();
|
||||
if repeats >= 3 {
|
||||
return Some(Ending::Threefold);
|
||||
}
|
||||
if pos.halfmoves() >= 100 {
|
||||
return Some(Ending::FiftyMoves);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ----- Maia's moves -------------------------------------------------------------------
|
||||
|
||||
/// A request for a move: the positions up to now, the ratings, the pause.
|
||||
struct Request {
|
||||
generation: u64,
|
||||
positions: Vec<Chess>,
|
||||
self_elo: u32,
|
||||
oppo_elo: u32,
|
||||
pause: Duration,
|
||||
}
|
||||
|
||||
/// The engine in a thread of its own: loads Maia once, answers requests after a pause.
|
||||
/// An answer for an older generation (after a take-back, a resignation) is dropped.
|
||||
pub struct Opponent {
|
||||
tx: Sender<Request>,
|
||||
rx: Receiver<(u64, Option<Move>)>,
|
||||
generation: u64,
|
||||
/// Loading failed: why (shown to the user).
|
||||
pub error: Arc<Mutex<Option<String>>>,
|
||||
pub thinking: bool,
|
||||
}
|
||||
|
||||
impl Opponent {
|
||||
pub fn start(weights: std::path::PathBuf, ctx: &egui::Context) -> Opponent {
|
||||
let (tx, req_rx) = channel::<Request>();
|
||||
let (ans_tx, rx) = channel();
|
||||
let error = Arc::new(Mutex::new(None));
|
||||
let err = error.clone();
|
||||
let ctx = ctx.clone();
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("maia".into())
|
||||
.spawn(move || {
|
||||
let maia = match maia::Maia::load(&weights) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
if let Ok(mut g) = err.lock() {
|
||||
*g = Some(e.to_string());
|
||||
}
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
};
|
||||
while let Ok(mut r) = req_rx.recv() {
|
||||
// Only the newest request counts.
|
||||
while let Ok(newer) = req_rx.try_recv() {
|
||||
r = newer;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let p = maia.predict(&r.positions, r.self_elo, r.oppo_elo);
|
||||
let m = maia::pick(&p, 1.0, random_unit());
|
||||
let rest = r.pause.saturating_sub(started.elapsed());
|
||||
std::thread::sleep(rest);
|
||||
if ans_tx.send((r.generation, m)).is_err() {
|
||||
return;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
Opponent {
|
||||
tx,
|
||||
rx,
|
||||
generation: 0,
|
||||
error,
|
||||
thinking: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks for a move in the last of `positions`.
|
||||
pub fn ask(&mut self, positions: Vec<Chess>, self_elo: u32, oppo_elo: u32, pause: Duration) {
|
||||
self.generation += 1;
|
||||
self.thinking = true;
|
||||
let _ = self.tx.send(Request {
|
||||
generation: self.generation,
|
||||
positions,
|
||||
self_elo,
|
||||
oppo_elo,
|
||||
pause,
|
||||
});
|
||||
}
|
||||
|
||||
/// Forgets what was asked (its answer will be dropped).
|
||||
pub fn forget(&mut self) {
|
||||
self.generation += 1;
|
||||
self.thinking = false;
|
||||
}
|
||||
|
||||
/// The move asked for last, when it has come.
|
||||
pub fn answer(&mut self) -> Option<Move> {
|
||||
let mut out = None;
|
||||
while let Ok((g, m)) = self.rx.try_recv() {
|
||||
if g == self.generation {
|
||||
self.thinking = false;
|
||||
out = m;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn failed(&self) -> Option<String> {
|
||||
self.error.lock().ok().and_then(|g| g.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A number in [0, 1).
|
||||
pub fn random_unit() -> f32 {
|
||||
let mut b = [0u8; 4];
|
||||
let _ = getrandom::fill(&mut b);
|
||||
(u32::from_le_bytes(b) >> 8) as f32 / (1u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// How long Maia "thinks" (it computes in a tenth of a second): about 1/30 of its time
|
||||
/// plus most of the increment, varied at random; fast in the opening and with one
|
||||
/// legal move; never so long that it could lose on time (docs/research/play-mode.md R15).
|
||||
pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Duration {
|
||||
let r = random_unit();
|
||||
// A log-normal-ish factor between 0.4 and 2.5.
|
||||
let factor = (0.4f32 * (2.5f32 / 0.4).powf(r)).clamp(0.4, 2.5);
|
||||
let secs = match clock {
|
||||
None => 0.5 + 1.5 * r,
|
||||
Some((left, inc)) => {
|
||||
let left = left.as_secs_f32();
|
||||
if left < 10.0 {
|
||||
0.2 + 0.8 * r
|
||||
} else {
|
||||
let mut t = (left / 30.0 + 0.75 * inc as f32) * factor;
|
||||
if ply < 10 {
|
||||
t *= 0.3;
|
||||
}
|
||||
t.clamp(0.4, (left / 8.0).min(60.0))
|
||||
}
|
||||
}
|
||||
};
|
||||
let secs = if only_move {
|
||||
secs.min(0.3 + 0.5 * r)
|
||||
} else {
|
||||
secs
|
||||
};
|
||||
Duration::from_secs_f32(secs)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chess_core::shakmaty::uci::UciMove;
|
||||
|
||||
#[test]
|
||||
fn speeds_as_lichess() {
|
||||
let s = |base, increment| TimeControl { base, increment }.speed();
|
||||
assert_eq!(s(60, 0), Speed::Bullet);
|
||||
assert_eq!(s(120, 1), Speed::Bullet);
|
||||
assert_eq!(s(180, 0), Speed::Blitz);
|
||||
assert_eq!(s(300, 3), Speed::Blitz);
|
||||
assert_eq!(s(420, 0), Speed::Blitz);
|
||||
assert_eq!(s(480, 0), Speed::Rapid);
|
||||
assert_eq!(s(900, 10), Speed::Rapid);
|
||||
assert_eq!(s(1500, 0), Speed::Classical);
|
||||
assert_eq!(s(15, 0), Speed::UltraBullet);
|
||||
assert_eq!(
|
||||
TimeControl {
|
||||
base: 300,
|
||||
increment: 3
|
||||
}
|
||||
.label(),
|
||||
"5+3"
|
||||
);
|
||||
assert_eq!(
|
||||
TimeControl {
|
||||
base: 30,
|
||||
increment: 0
|
||||
}
|
||||
.label(),
|
||||
"½+0"
|
||||
);
|
||||
assert_eq!(
|
||||
TimeControl {
|
||||
base: 300,
|
||||
increment: 3
|
||||
}
|
||||
.pgn(),
|
||||
"300+3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_runs_after_first_moves() {
|
||||
let mut c = Clock::new(TimeControl {
|
||||
base: 60,
|
||||
increment: 2,
|
||||
});
|
||||
let t0 = Instant::now();
|
||||
c.moved(Color::White, t0); // the first move takes nothing
|
||||
assert_eq!(c.left(Color::White, t0), Duration::from_secs(62));
|
||||
// Black's first move: no time taken either.
|
||||
c.moved(Color::Black, t0 + Duration::from_secs(5));
|
||||
assert_eq!(
|
||||
c.left(Color::Black, t0 + Duration::from_secs(5)),
|
||||
Duration::from_secs(62)
|
||||
);
|
||||
// White thinks 10 s.
|
||||
let t1 = t0 + Duration::from_secs(15);
|
||||
assert_eq!(c.left(Color::White, t1), Duration::from_secs(52));
|
||||
c.moved(Color::White, t1);
|
||||
assert_eq!(c.left(Color::White, t1), Duration::from_secs(54));
|
||||
assert_eq!(c.running(), Some(Color::Black));
|
||||
assert_eq!(clock_text(Duration::from_millis(9_450)), "0:09.4");
|
||||
assert_eq!(clock_text(Duration::from_secs(298)), "4:58");
|
||||
assert_eq!(clock_text(Duration::from_secs(3723)), "1:02:03");
|
||||
assert_eq!(clk_command(Duration::from_secs(298)), "[%clk 0:04:58]");
|
||||
assert_eq!(
|
||||
Clock::new(TimeControl {
|
||||
base: 180,
|
||||
increment: 0
|
||||
})
|
||||
.low(),
|
||||
Duration::from_secs(22)
|
||||
);
|
||||
}
|
||||
|
||||
fn play(moves: &[&str]) -> Vec<Chess> {
|
||||
let mut pos = Chess::default();
|
||||
let mut out = vec![pos.clone()];
|
||||
for m in moves {
|
||||
let m = m.parse::<UciMove>().unwrap().to_move(&pos).unwrap();
|
||||
pos.play_unchecked(m);
|
||||
out.push(pos.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endings() {
|
||||
let mate = play(&["f2f3", "e7e5", "g2g4", "d8h4"]);
|
||||
assert_eq!(
|
||||
ending(&mate),
|
||||
Some(Ending::Checkmate {
|
||||
winner: Color::Black
|
||||
})
|
||||
);
|
||||
let rep = play(&[
|
||||
"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8",
|
||||
]);
|
||||
assert_eq!(ending(&rep), Some(Ending::Threefold));
|
||||
assert_eq!(ending(&rep[..rep.len() - 1]), None);
|
||||
assert_eq!(ending(&play(&["e2e4"])), None);
|
||||
assert_eq!(
|
||||
Ending::Time {
|
||||
loser: Color::White,
|
||||
draw: false
|
||||
}
|
||||
.result(),
|
||||
chess_core::GameResult::BlackWins
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pauses_never_lose_on_time() {
|
||||
for _ in 0..200 {
|
||||
let p = pause(Some((Duration::from_secs(20), 0)), 30, false);
|
||||
assert!(p <= Duration::from_millis(2500), "{p:?}");
|
||||
let p = pause(Some((Duration::from_secs(5), 0)), 30, false);
|
||||
assert!(p <= Duration::from_millis(1000));
|
||||
}
|
||||
assert_eq!(strength_like(1350), 1400);
|
||||
assert_eq!(strength_like(300), 600);
|
||||
}
|
||||
}
|
||||
|
||||
// ----- a game being played ------------------------------------------------------------
|
||||
|
||||
/// A game against Maia in progress (lives in the game screen while it is played).
|
||||
pub struct Session {
|
||||
pub user: Color,
|
||||
pub strength: u32,
|
||||
pub user_elo: Option<u32>,
|
||||
pub clock: Option<Clock>,
|
||||
pub opponent: Opponent,
|
||||
/// The low-time warning was given (once).
|
||||
pub warned: bool,
|
||||
/// «Resign?» waits for the second click.
|
||||
pub resign_asked: bool,
|
||||
}
|
||||
|
||||
/// What the play dialog starts.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Start {
|
||||
pub user: Color,
|
||||
pub strength: u32,
|
||||
pub user_elo: Option<u32>,
|
||||
pub user_name: String,
|
||||
pub clock: Option<TimeControl>,
|
||||
}
|
||||
|
||||
// ----- the dialog ---------------------------------------------------------------------
|
||||
|
||||
/// «Play against the computer»: name and rating, colour, time, strength.
|
||||
pub struct Dialog {
|
||||
name: String,
|
||||
rating: String,
|
||||
prefs: PlayPrefs,
|
||||
custom: bool,
|
||||
download: Option<crate::maia_download::Download>,
|
||||
focus: bool,
|
||||
}
|
||||
|
||||
pub enum DialogOutcome {
|
||||
Play(Start),
|
||||
Cancel,
|
||||
}
|
||||
|
||||
impl Dialog {
|
||||
pub fn new(settings: &crate::settings::Settings) -> Dialog {
|
||||
let prefs = settings.play.clone();
|
||||
let custom = prefs.clock.is_some_and(|c| !PRESETS.contains(&c));
|
||||
Dialog {
|
||||
name: settings.your_name.clone(),
|
||||
rating: settings.rating.map(|r| r.to_string()).unwrap_or_default(),
|
||||
prefs,
|
||||
custom,
|
||||
download: None,
|
||||
focus: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn rating(&self) -> Option<u32> {
|
||||
self.rating
|
||||
.trim()
|
||||
.parse::<u32>()
|
||||
.ok()
|
||||
.filter(|r| (100..=3500).contains(r))
|
||||
}
|
||||
|
||||
/// Draws the dialog; on «Play» the choices are written into `settings`.
|
||||
pub fn show(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
settings: &mut crate::settings::Settings,
|
||||
) -> Option<DialogOutcome> {
|
||||
use egui::RichText;
|
||||
let mut out = None;
|
||||
let installed = crate::maia_download::installed();
|
||||
egui::Modal::new(egui::Id::new("play_dialog")).show(ctx, |ui| {
|
||||
ui.set_width(460.0);
|
||||
ui.heading(tr("Play against the computer"));
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"Maia plays like a human of the chosen rating: it makes the moves people of that level make, mistakes included.",
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
ui.add_space(10.0);
|
||||
|
||||
// You.
|
||||
ui.label(RichText::new(tr("You")).strong());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Name:"));
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut self.name).desired_width(200.0));
|
||||
if std::mem::take(&mut self.focus) && self.name.is_empty() {
|
||||
r.request_focus();
|
||||
}
|
||||
ui.label(tr("Rating:"));
|
||||
let r = ui.add(
|
||||
egui::TextEdit::singleline(&mut self.rating)
|
||||
.desired_width(60.0)
|
||||
.hint_text("1500"),
|
||||
);
|
||||
if r.changed() {
|
||||
self.rating.retain(|c| c.is_ascii_digit());
|
||||
self.rating.truncate(4);
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(tr("Not required; the opponent's strength is chosen relative to it."))
|
||||
.weak()
|
||||
.size(11.5),
|
||||
);
|
||||
ui.add_space(10.0);
|
||||
|
||||
// Colour.
|
||||
ui.label(RichText::new(tr("Your colour")).strong());
|
||||
ui.horizontal(|ui| {
|
||||
for (c, label) in [
|
||||
(ColorChoice::White, tr("♔ White")),
|
||||
(ColorChoice::Random, tr("Random")),
|
||||
(ColorChoice::Black, tr("♚ Black")),
|
||||
] {
|
||||
ui.selectable_value(&mut self.prefs.color, c, label);
|
||||
}
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
|
||||
// Time.
|
||||
ui.label(RichText::new(tr("Time")).strong());
|
||||
egui::Grid::new("play_presets")
|
||||
.spacing(egui::vec2(6.0, 6.0))
|
||||
.show(ui, |ui| {
|
||||
for (k, tc) in PRESETS.iter().enumerate() {
|
||||
let on = !self.custom && self.prefs.clock == Some(*tc);
|
||||
let text = format!("{}\n{}", tc.label(), tc.speed().name());
|
||||
if ui
|
||||
.add_sized([96.0, 40.0], egui::Button::selectable(on, text))
|
||||
.clicked()
|
||||
{
|
||||
self.prefs.clock = Some(*tc);
|
||||
self.custom = false;
|
||||
}
|
||||
if k % 4 == 3 {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
if ui
|
||||
.add_sized([96.0, 40.0], egui::Button::selectable(self.custom, tr("Custom")))
|
||||
.clicked()
|
||||
{
|
||||
self.custom = true;
|
||||
if self.prefs.clock.is_none() {
|
||||
self.prefs.clock = Some(TimeControl { base: 600, increment: 0 });
|
||||
}
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let none = self.prefs.clock.is_none();
|
||||
if ui.selectable_label(none, tr("No clock")).clicked() {
|
||||
self.prefs.clock = None;
|
||||
self.custom = false;
|
||||
}
|
||||
});
|
||||
if self.custom
|
||||
&& let Some(tc) = self.prefs.clock.as_mut()
|
||||
{
|
||||
let mut b = CUSTOM_BASES.iter().position(|&x| x >= tc.base).unwrap_or(14);
|
||||
let mut i = CUSTOM_INCREMENTS
|
||||
.iter()
|
||||
.position(|&x| x >= tc.increment)
|
||||
.unwrap_or(0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Minutes:"));
|
||||
ui.add(egui::Slider::new(&mut b, 0..=CUSTOM_BASES.len() - 1).show_value(false));
|
||||
ui.label(TimeControl { base: CUSTOM_BASES[b], increment: 0 }.label().trim_end_matches("+0"));
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Increment, s:"));
|
||||
ui.add(
|
||||
egui::Slider::new(&mut i, 0..=CUSTOM_INCREMENTS.len() - 1).show_value(false),
|
||||
);
|
||||
ui.label(CUSTOM_INCREMENTS[i].to_string());
|
||||
});
|
||||
tc.base = CUSTOM_BASES[b];
|
||||
tc.increment = CUSTOM_INCREMENTS[i];
|
||||
if tc.base == 0 && tc.increment == 0 {
|
||||
tc.increment = 1;
|
||||
}
|
||||
ui.label(
|
||||
RichText::new(format!("{} · {}", tc.label(), tc.speed().name())).weak(),
|
||||
);
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
|
||||
// Strength.
|
||||
ui.label(RichText::new(tr("Opponent")).strong());
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::Slider::new(&mut self.prefs.strength, STRENGTH_MIN..=STRENGTH_MAX)
|
||||
.step_by(100.0)
|
||||
.show_value(false),
|
||||
);
|
||||
ui.label(RichText::new(format!("Maia {}", self.prefs.strength)).strong());
|
||||
});
|
||||
let rating = self.rating();
|
||||
ui.add_enabled_ui(rating.is_some(), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (label, delta) in [(tr("Weaker"), -200), (tr("As me"), 0), (tr("Stronger"), 200)] {
|
||||
if ui.button(label).clicked()
|
||||
&& let Some(r) = rating
|
||||
{
|
||||
self.prefs.strength =
|
||||
strength_like((r as i32 + delta).max(0) as u32);
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
.response
|
||||
.on_disabled_hover_text(tr("Enter your rating to choose relative to it"));
|
||||
ui.label(
|
||||
RichText::new(tr("Maia's ratings are Lichess ratings: club and federation ratings are usually lower."))
|
||||
.weak()
|
||||
.size(11.5),
|
||||
);
|
||||
ui.add_space(10.0);
|
||||
|
||||
// Maia itself: downloaded once.
|
||||
let mut ready = installed.is_some();
|
||||
if !ready {
|
||||
match self.download.as_ref().map(|d| d.stage()) {
|
||||
None => {
|
||||
ui.label(trf_size());
|
||||
if ui.button(tr("Download Maia")).clicked() {
|
||||
self.download = Some(crate::maia_download::Download::start(ctx));
|
||||
}
|
||||
}
|
||||
Some(crate::maia_download::Stage::Downloading { done }) => {
|
||||
ui.add(
|
||||
egui::ProgressBar::new(done as f32 / crate::maia_download::SIZE as f32)
|
||||
.show_percentage(),
|
||||
);
|
||||
}
|
||||
Some(crate::maia_download::Stage::Checking) => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Spinner::new());
|
||||
ui.label(tr("Checking…"));
|
||||
});
|
||||
}
|
||||
Some(crate::maia_download::Stage::Done(_)) => ready = true,
|
||||
Some(crate::maia_download::Stage::Failed(e)) => {
|
||||
ui.label(RichText::new(e).color(ui.visuals().error_fg_color));
|
||||
if ui.button(tr("Try again")).clicked() {
|
||||
self.download = Some(crate::maia_download::Download::start(ctx));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ui.add_space(6.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let play = ui
|
||||
.add_enabled_ui(ready, |ui| crate::widgets::primary(ui, tr("Play")))
|
||||
.inner;
|
||||
let enter = ready && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
if play.clicked() || enter {
|
||||
let user = match self.prefs.color {
|
||||
ColorChoice::White => Color::White,
|
||||
ColorChoice::Black => Color::Black,
|
||||
ColorChoice::Random => {
|
||||
if random_unit() < 0.5 {
|
||||
Color::White
|
||||
} else {
|
||||
Color::Black
|
||||
}
|
||||
}
|
||||
};
|
||||
settings.your_name = self.name.trim().to_owned();
|
||||
settings.rating = rating;
|
||||
settings.play = self.prefs.clone();
|
||||
out = Some(DialogOutcome::Play(Start {
|
||||
user,
|
||||
strength: self.prefs.strength,
|
||||
user_elo: rating,
|
||||
user_name: self.name.trim().to_owned(),
|
||||
clock: self.prefs.clock,
|
||||
}));
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
out = Some(DialogOutcome::Cancel);
|
||||
}
|
||||
});
|
||||
});
|
||||
if out.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
out = Some(DialogOutcome::Cancel);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn trf_size() -> String {
|
||||
crate::i18n::trf(
|
||||
"Maia is downloaded once ({mb} MB, from huggingface.co, the authors' own file).",
|
||||
&[("mb", &crate::maia_download::SIZE.div_ceil(1_000_000))],
|
||||
)
|
||||
}
|
||||
|
||||
/// A game just played: what the result strip says.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct End {
|
||||
pub ending: Ending,
|
||||
pub user: Color,
|
||||
pub start: Start,
|
||||
/// The clocks at the end (user, Maia).
|
||||
pub left: Option<(Duration, Duration)>,
|
||||
}
|
||||
|
||||
impl End {
|
||||
/// «You won» / «You lost» / «Draw» / «You resigned».
|
||||
pub fn heading(&self) -> &'static str {
|
||||
match self.ending {
|
||||
Ending::Resigned { .. } => tr("You resigned"),
|
||||
e => match e.result() {
|
||||
chess_core::GameResult::Draw => tr("Draw"),
|
||||
r if r == Ending::Checkmate { winner: self.user }.result() => tr("You won"),
|
||||
_ => tr("You lost"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(&self) -> &'static str {
|
||||
match self.ending {
|
||||
Ending::Checkmate { .. } => tr("checkmate"),
|
||||
Ending::Stalemate => tr("stalemate"),
|
||||
Ending::InsufficientMaterial => tr("neither side can checkmate"),
|
||||
Ending::Threefold => tr("the position occurred three times"),
|
||||
Ending::FiftyMoves => tr("50 moves without a capture or a pawn move"),
|
||||
Ending::Time { draw: true, .. } => tr("time is up, but Maia cannot checkmate"),
|
||||
Ending::Time { .. } => tr("time is up"),
|
||||
Ending::Resigned { .. } => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -139,6 +139,10 @@ pub struct Settings {
|
|||
pub new_database_dir: Option<PathBuf>,
|
||||
/// The database a game was last added to (preselected in the chooser).
|
||||
pub last_target: Option<PathBuf>,
|
||||
/// The user's rating (optional): the strength of Maia is chosen relative to it.
|
||||
pub rating: Option<u32>,
|
||||
/// The last choices of the play dialog.
|
||||
pub play: crate::play::PlayPrefs,
|
||||
}
|
||||
|
||||
/// Options of the whole-game analysis (the engine is the active one).
|
||||
|
|
@ -203,6 +207,8 @@ impl Default for Settings {
|
|||
your_name: String::new(),
|
||||
new_database_dir: None,
|
||||
last_target: None,
|
||||
rating: None,
|
||||
play: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue