res.rs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. use crate::com::*;
  2. use crate::consts;
  3. use crate::types::World;
  4. use specs::world::{Builder, WorldExt};
  5. use std::path::Path;
  6. #[derive(Debug, Default)]
  7. pub struct KeySet {
  8. keys: std::collections::HashSet<winit::VirtualKeyCode>,
  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: &winit::VirtualKeyCode) -> bool {
  17. self.keys.contains(kc)
  18. }
  19. pub fn insert(&mut self, kc: winit::VirtualKeyCode) {
  20. self.keys.insert(kc);
  21. }
  22. pub fn remove(&mut self, kc: &winit::VirtualKeyCode) {
  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, tilesets, ..
  40. } = tiled::parse_file(path.as_ref()).unwrap();
  41. for (phase, layer) in DRAW_LAYERS.iter().zip(layers) {
  42. for (row, y) in layer.tiles.iter().zip(0..) {
  43. for (&n, x) in row.iter().zip(0..) {
  44. if n != 0 {
  45. let x = x as f32 * consts::TILE_SIZE;
  46. let y = y as f32 * consts::TILE_SIZE;
  47. let u = ((n - 1) % 32) as u8;
  48. let v = ((n - u as u32 - 1) / 32) as u8;
  49. let blocking = if tilesets[0].tiles[(n-1) as usize].properties["pass"]
  50. == tiled::PropertyValue::BoolValue(false) {
  51. let mut h = w.write_resource::<World>();
  52. Some(Blocking::new_box(&mut h))
  53. } else {
  54. None
  55. };
  56. let mut e = w
  57. .create_entity()
  58. .with(Position { x, y })
  59. .with(Sprite { u, v });
  60. e = match phase {
  61. DrawLayer::Background => e.with(Background),
  62. DrawLayer::Foreground => e.with(Foreground),
  63. DrawLayer::Decoration => e.with(Decoration),
  64. };
  65. let e = if let Some(b) = blocking { e.with(b) } else { e };
  66. e.build();
  67. }
  68. }
  69. }
  70. }
  71. // create the player
  72. let ball = {
  73. let mut h = w.write_resource::<World>();
  74. Blocking::new_ball(&mut h)
  75. };
  76. w.create_entity()
  77. .with(Position {
  78. x: 3.0 * consts::TILE_SIZE,
  79. y: 3.0 * consts::TILE_SIZE,
  80. })
  81. .with(Sprite { u: 8, v: 0 })
  82. .with(Velocity { dx: 0.0, dy: 0.0 })
  83. .with(Foreground)
  84. .with(Controlled)
  85. .with(Collision {
  86. has_collision: false,
  87. })
  88. .with(ball)
  89. .build();
  90. }