| 1 |
use std::time::Duration; |
| 2 |
|
| 3 |
use sdl2::{event::Event, keyboard::Keycode}; |
| 4 |
|
| 5 |
use crate::{ |
| 6 |
game_context::{GameContext}, |
| 7 |
renderer::Renderer, |
| 8 |
}; |
| 9 |
|
| 10 |
pub struct App { |
| 11 |
pub sdl: sdl2::Sdl, |
| 12 |
pub game_context: GameContext, |
| 13 |
} |
| 14 |
|
| 15 |
impl App { |
| 16 |
pub fn new() -> Result<Self, String> { |
| 17 |
let sdl: sdl2::Sdl = sdl2::init()?; |
| 18 |
let game_context: GameContext = GameContext::new()?; |
| 19 |
|
| 20 |
Ok(Self { sdl, game_context }) |
| 21 |
} |
| 22 |
|
| 23 |
pub fn run(&mut self, renderer: &mut Renderer) { |
| 24 |
let mut event_pump = self.sdl.event_pump().unwrap(); |
| 25 |
let mut frame_counter: u64 = 0; |
| 26 |
'running: loop { |
| 27 |
for event in event_pump.poll_iter() { |
| 28 |
match event { |
| 29 |
Event::Quit { .. } |
| 30 |
| Event::KeyDown { |
| 31 |
keycode: Some(Keycode::Q), |
| 32 |
.. |
| 33 |
} => break 'running, |
| 34 |
Event::KeyDown { |
| 35 |
keycode: Some(keycode), |
| 36 |
.. |
| 37 |
} => match keycode { |
| 38 |
Keycode::W => self.game_context.move_up(), |
| 39 |
Keycode::A => self.game_context.move_left(), |
| 40 |
Keycode::S => self.game_context.move_down(), |
| 41 |
Keycode::D => self.game_context.move_right(), |
| 42 |
Keycode::Escape => self.game_context.toggle_pause(), |
| 43 |
_ => {} |
| 44 |
}, |
| 45 |
_ => {} |
| 46 |
} |
| 47 |
} |
| 48 |
::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60)); |
| 49 |
|
| 50 |
frame_counter += 1; |
| 51 |
if frame_counter.is_multiple_of(20) { |
| 52 |
self.game_context.next_tick(); |
| 53 |
frame_counter = 0; |
| 54 |
} |
| 55 |
renderer.draw(self).expect("Failed to render!") |
| 56 |
} |
| 57 |
} |
| 58 |
} |