resources.rs 2.9 KB

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