res.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. use crate::consts;
  2. use crate::com::*;
  3. use specs::world::Builder;
  4. use std::path::Path;
  5. use sdl2::keyboard as sdl;
  6. #[derive(Debug, Default)]
  7. pub struct KeySet {
  8. keys: std::collections::HashSet<sdl::Keycode>,
  9. }
  10. impl KeySet {
  11. pub fn new() -> KeySet {
  12. KeySet {
  13. keys: std::collections::HashSet::new(),
  14. }
  15. }
  16. pub fn contains(&self, kc: &sdl::Keycode) -> bool {
  17. self.keys.contains(kc)
  18. }
  19. pub fn insert(&mut self, kc: sdl::Keycode) {
  20. self.keys.insert(kc);
  21. }
  22. pub fn remove(&mut self, kc: &sdl::Keycode) {
  23. self.keys.remove(kc);
  24. }
  25. }
  26. #[derive(Debug, Copy, Clone)]
  27. enum DrawLayer {
  28. Background,
  29. Foreground,
  30. Decoration,
  31. }
  32. static DRAW_LAYERS: [DrawLayer;3] = [
  33. DrawLayer::Background,
  34. DrawLayer::Foreground,
  35. DrawLayer::Decoration,
  36. ];
  37. pub fn world_from_file<P: AsRef<Path>>(w: &mut specs::World, path: P) {
  38. let tiled::Map {
  39. layers,
  40. tilesets,
  41. ..
  42. } = tiled::parse_file(path.as_ref()).unwrap();
  43. for (phase, layer) in DRAW_LAYERS.iter().zip(layers) {
  44. for (row, y) in layer.tiles.iter().zip(0..) {
  45. for (&n, x) in row.iter().zip(0..) {
  46. if n != 0 {
  47. let x = x as f32 * consts::TILE_SIZE;
  48. let y = y as f32 * consts::TILE_SIZE;
  49. let u = ((n - 1) % 32) as u8;
  50. let v = ((n - u as u32 - 1) / 32) as u8;
  51. let mut e = w.create_entity()
  52. .with(Position { x, y })
  53. .with(Sprite { u, v });
  54. e = match phase {
  55. DrawLayer::Background => e.with(Background),
  56. DrawLayer::Foreground => e.with(Foreground),
  57. DrawLayer::Decoration => e.with(Decoration),
  58. };
  59. let e = if tilesets[0].tiles[n as usize].properties["pass"] ==
  60. tiled::PropertyValue::BoolValue(false) {
  61. e.with(Blocking)
  62. } else {
  63. e
  64. };
  65. e.build();
  66. }
  67. }
  68. }
  69. }
  70. // create the player
  71. w.create_entity()
  72. .with(Position {
  73. x: 3.0 * consts::TILE_SIZE,
  74. y: 3.0 * consts::TILE_SIZE,
  75. })
  76. .with(Sprite { u: 8, v: 0 })
  77. .with(Velocity { dx: 0.0, dy: 0.0 })
  78. .with(Foreground)
  79. .with(Controlled)
  80. .with(Collision { has_collision: false })
  81. .build();
  82. }