game.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use ggez::event::EventHandler;
  2. use ggez::{Context, GameResult};
  3. use specs::world::WorldExt;
  4. use crate::{components, resources, sys};
  5. /// The shared values that the game state needs, specifically as the specs world
  6. pub struct MyGame {
  7. pub world: specs::World,
  8. }
  9. impl MyGame {
  10. // setup the necessary initial state for `MyGame`, inserting the
  11. // relevant resources into it
  12. pub fn setup(ctx: &mut Context) -> GameResult<MyGame> {
  13. let mut world = specs::World::new();
  14. components::register(&mut world);
  15. world.insert(ncollide2d::world::CollisionWorld::<f32, specs::Entity>::new(0.1));
  16. resources::world_from_file(&mut world, "assets/main.tmx");
  17. let image = ggez::graphics::Image::new(ctx, "/spritesheet.png")?;
  18. let mut sprites = ggez::graphics::spritebatch::SpriteBatch::new(image);
  19. sprites.set_filter(ggez::graphics::FilterMode::Nearest);
  20. world.insert(sprites);
  21. world.insert(resources::KeySet::new());
  22. Ok(MyGame { world })
  23. }
  24. }
  25. impl EventHandler for MyGame {
  26. fn update(&mut self, _ctx: &mut Context) -> GameResult<()> {
  27. sys::input::systems(self);
  28. sys::physics::systems(self);
  29. Ok(())
  30. }
  31. fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
  32. sys::drawing::systems(self, ctx)
  33. }
  34. fn key_down_event(
  35. &mut self,
  36. ctx: &mut Context,
  37. keycode: winit::VirtualKeyCode,
  38. _keymod: ggez::event::KeyMods,
  39. _repeat: bool,
  40. ) {
  41. if keycode == winit::VirtualKeyCode::Escape {
  42. ggez::event::quit(ctx);
  43. }
  44. self.world
  45. .write_resource::<resources::KeySet>()
  46. .insert(keycode);
  47. }
  48. fn key_up_event(
  49. &mut self,
  50. _ctx: &mut Context,
  51. keycode: winit::VirtualKeyCode,
  52. _keymod: ggez::event::KeyMods,
  53. ) {
  54. self.world
  55. .write_resource::<resources::KeySet>()
  56. .remove(&keycode);
  57. }
  58. }