diff --git a/src/lib.rs b/src/lib.rs index d9fc4f1..1656937 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,13 @@ +use std::cell::Cell; + use sdl2::{video::{WindowBuildError, Window}, IntegerOrSdlError, render::Canvas, EventPump}; +pub use sdl2::pixels::Color; +pub use sdl2::keyboard::Keycode; +pub use sdl2::event::Event; + + +#[derive(Debug)] pub struct CatboxError(String); impl From for CatboxError { @@ -23,9 +31,10 @@ impl From for CatboxError { pub type Result = std::result::Result; pub struct Game { - title: String, - width: u32, - height: u32, + pub title: String, + pub width: u32, + pub height: u32, + stopped: Cell } impl Game { @@ -33,11 +42,12 @@ impl Game { Self { title: title.to_string(), width, - height + height, + stopped: Cell::new(false) } } - pub fn run, &EventPump)>(&self, func: F) -> Result<()> { + pub fn run, &mut EventPump)>(&self, func: F) -> Result<()> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; @@ -50,10 +60,17 @@ impl Game { let mut event_pump = sdl_context.event_pump()?; loop { - func(&canvas, &event_pump); + if self.stopped.get() { + break; + } + func(&mut canvas, &mut event_pump); canvas.present(); } Ok(()) } + + pub fn terminate(&self) { + self.stopped.set(true); + } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..a6080c0 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,16 @@ +use catbox::{Game, Keycode, Event}; + +fn main() { + let mut game = Game::new("catbox demo", 1000, 800); + + game.run(|canvas, event_pump| { + canvas.set_draw_color(catbox::Color::RGB(0, 59, 111)); + canvas.clear(); + for event in event_pump.poll_iter() { + match event { + Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => game.terminate(), + _ => {} + } + } + }).unwrap(); +} \ No newline at end of file