+
+ pub fn start(&mut self) {
+ let mut frame_count: u64 = 0;
+ let mut fps_time = PreciseTime::now();
+ let mut last_time = PreciseTime::now();
+
+ 'running: loop {
+ if let Err(_) = self.handle_events() {
+ break 'running;
+ }
+
+ let duration =
+ last_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as Nanoseconds;
+ last_time = PreciseTime::now();
+ self.state.update(duration);
+
+ self.render();
+
+ frame_count += 1;
+ if frame_count == FPS as u64 {
+ let duration = fps_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as f64
+ / 1_000_000_000.0;
+ println!("fps: {}", frame_count as f64 / duration);
+ frame_count = 0;
+ fps_time = PreciseTime::now();
+ }
+ }
+
+ self.state.leave();
+ }
+
+ fn handle_events(&mut self) -> Result<(), ()> {
+ for event in self.event_pump.poll_iter() {
+ match event {
+ Event::Quit { .. }
+ | Event::KeyDown {
+ keycode: Some(Keycode::Escape),
+ ..
+ } => {
+ return Err(())
+ }
+ Event::KeyDown {
+ keycode: Some(Keycode::F11),
+ ..
+ } => {
+ match self.canvas.window().fullscreen_state() {
+ FullscreenType::Off => self
+ .canvas
+ .window_mut()
+ .set_fullscreen(FullscreenType::Desktop),
+ _ => self.canvas.window_mut().set_fullscreen(FullscreenType::Off),
+ }
+ .unwrap();
+ }
+ Event::Window {
+ win_event: WindowEvent::Resized(x, y),
+ ..
+ } => {
+ println!("window resized({}, {})", x, y)
+ }
+ Event::Window {
+ win_event: WindowEvent::Maximized,
+ ..
+ } => {
+ println!("window maximized")
+ }
+ Event::Window {
+ win_event: WindowEvent::Restored,
+ ..
+ } => {
+ println!("window restored")
+ }
+ Event::Window {
+ win_event: WindowEvent::Enter,
+ ..
+ } => {
+ println!("window enter")
+ }
+ Event::Window {
+ win_event: WindowEvent::Leave,
+ ..
+ } => {
+ println!("window leave")
+ }
+ Event::Window {
+ win_event: WindowEvent::FocusGained,
+ ..
+ } => {
+ println!("window focus gained")
+ }
+ Event::Window {
+ win_event: WindowEvent::FocusLost,
+ ..
+ } => {
+ println!("window focus lost")
+ }
+ _ => self.state.on_event(event),
+ }
+ }
+ Ok(())
+ }
+
+ fn render(&mut self) {
+ self.canvas.set_draw_color(Color::RGB(0, 0, 0));
+ self.canvas.clear();
+ self.state.render(&mut self.canvas, &mut self.sprites);
+ self.canvas.present();
+ }