use pancurses::{cbreak, curs_set, endwin, has_colors, initscr, noecho, start_color, Window};
use crate::{color, prelude::Stage};
pub struct Game<G> {
globals: G,
running: bool,
win: Window,
}
impl<G> Drop for Game<G> {
fn drop(&mut self) {
endwin();
}
}
impl<G> Game<G> {
pub fn new(initial_globals: G) -> Self {
let win = Self::init();
Self {
globals: initial_globals,
running: true,
win,
}
}
pub fn with_colors(initial_globals: G) -> Option<Self> {
let win = Self::init();
if !has_colors() {
endwin();
return None;
}
start_color();
color::init_colors();
Some(Self {
globals: initial_globals,
running: true,
win,
})
}
fn init() -> Window {
let win = initscr();
win.keypad(true);
win.nodelay(true);
cbreak();
noecho();
curs_set(0);
win
}
pub fn globals(&self) -> &G {
&self.globals
}
pub fn globals_mut(&mut self) -> &mut G {
&mut self.globals
}
pub fn is_running(&self) -> bool {
self.win().refresh();
self.running
}
pub fn running(&self) -> bool {
self.running
}
pub fn start(&mut self) {
self.running = true;
}
pub fn stop(&mut self) {
self.running = false;
}
pub fn win(&self) -> &Window {
&self.win
}
pub fn win_mut(&mut self) -> &mut Window {
&mut self.win
}
pub fn perform<T, E>(&mut self, stage: &mut Stage<T, E, G>) -> Result<(), E> {
stage.draw(self)?;
stage.update(self)?;
Ok(())
}
}