monorepo/kifu/gtk/src/view_models/game_view_model.rs

87 lines
2.8 KiB
Rust
Raw Normal View History

/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along with Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
use async_std::{
channel::Receiver,
task::{spawn, yield_now, JoinHandle},
};
use kifu_core::{Color, Core, CoreNotification, Goban, Observable, Player};
use std::{cell::RefCell, rc::Rc, time::Duration};
pub struct GameState {
goban: Goban,
white_clock: Duration,
black_clock: Duration,
white_score: f32,
black_score: f32,
current: Color,
}
struct GameViewModelPrivate {
white: Player, /* Maybe this should be PlayerState, instead, combining the player info, current clock, and current captures. */
black: Player,
state: GameState,
}
/// The Game View Model manages the current state of the game. It shows the two player cards, the board, the current capture count, the current player, and it maintains the UI for the clock (bearing in mind that the real clock is managed in the core). This view model should only be created once the details of the game, whether a game in progress or a new game (this view model won't know the difference) is known.
pub struct GameViewModel {
core: Core,
widget: gtk::Box,
data: Rc<RefCell<GameViewModelPrivate>>,
}
impl GameViewModelPrivate {
fn handle(&mut self, message: CoreNotification) {}
}
impl GameViewModel {
pub fn new(white: Player, black: Player, game: GameState, core: Core) -> Self {
let data = Rc::new(RefCell::new(GameViewModelPrivate {
white,
black,
state: game,
}));
let s = Self {
core,
widget: gtk::Box::new(gtk::Orientation::Horizontal, 0),
data,
};
let notifications = s.core.subscribe();
let data = s.data.clone();
glib::spawn_future_local(Self::listen(notifications, data));
s
}
async fn listen(
notifications: Receiver<CoreNotification>,
data: Rc<RefCell<GameViewModelPrivate>>,
) {
loop {
match notifications.recv().await {
Ok(msg) => data.borrow_mut().handle(msg),
Err(err) => {
unimplemented!("Should display an error message in the UI: {}", err)
}
}
yield_now().await;
}
}
}