res.rs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. use crate::com::*;
  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 mut e = w
  49. .create_entity()
  50. .with(Position { x, y })
  51. .with(Sprite { u, v });
  52. e = match phase {
  53. DrawLayer::Background => e.with(Background),
  54. DrawLayer::Foreground => e.with(Foreground),
  55. DrawLayer::Decoration => e.with(Decoration),
  56. };
  57. let e = if tilesets[0].tiles[(n-1) as usize].properties["pass"]
  58. == tiled::PropertyValue::BoolValue(false)
  59. {
  60. e.with(Blocking::new())
  61. } else {
  62. e
  63. };
  64. e.build();
  65. }
  66. }
  67. }
  68. }
  69. // create the player
  70. w.create_entity()
  71. .with(Position {
  72. x: 3.0 * consts::TILE_SIZE,
  73. y: 3.0 * consts::TILE_SIZE,
  74. })
  75. .with(Sprite { u: 8, v: 0 })
  76. .with(Velocity { dx: 0.0, dy: 0.0 })
  77. .with(Foreground)
  78. .with(Controlled)
  79. .with(Collision {
  80. has_collision: false,
  81. })
  82. .with(Blocking {
  83. volume: Box::new(ncollide2d::shape::Ball::new(10.0)),
  84. })
  85. .build();
  86. }