map.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. use rltk::{ RGB, Rltk};
  2. use super::{Rect};
  3. use std::cmp::{max, min};
  4. #[derive(PartialEq, Copy, Clone)]
  5. pub enum TileType {
  6. Wall,
  7. Floor
  8. }
  9. pub fn xy_idx(x: i32, y: i32) -> usize {
  10. (y as usize * 80) + x as usize
  11. }
  12. /// Makes a map with solid boundaries and 400 randomly placed walls. No guarantees that it won't
  13. /// look awful.
  14. pub fn new_map_test() -> Vec<TileType> {
  15. let mut map = vec![TileType::Floor; 80*50];
  16. // Make the boundaries walls
  17. for x in 0..80 {
  18. map[xy_idx(x, 0)] = TileType::Wall;
  19. map[xy_idx(x, 49)] = TileType::Wall;
  20. }
  21. for y in 0..50 {
  22. map[xy_idx(0, y)] = TileType::Wall;
  23. map[xy_idx(79, y)] = TileType::Wall;
  24. }
  25. // Now we'll randomly splat a bunch of walls. It won't be pretty, but it's a decent illustration.
  26. // First, obtain the thread-local RNG:
  27. let mut rng = rltk::RandomNumberGenerator::new();
  28. for _i in 0..400 {
  29. let x = rng.roll_dice(1, 79);
  30. let y = rng.roll_dice(1, 49);
  31. let idx = xy_idx(x, y);
  32. if idx != xy_idx(40, 25) {
  33. map[idx] = TileType::Wall;
  34. }
  35. }
  36. return map
  37. }
  38. pub fn new_map_rooms_and_corridors() -> Vec<TileType> {
  39. let mut map = vec![TileType::Wall; 80*50];
  40. let room1 = Rect::new(20, 15, 10, 15);
  41. let room2 = Rect::new(35, 15, 10, 15);
  42. apply_room_to_map(&room1, &mut map);
  43. apply_room_to_map(&room2, &mut map);
  44. map
  45. }
  46. fn apply_room_to_map(room : &Rect, map: &mut [TileType]) {
  47. for y in room.y1 +1 ..= room.y2 {
  48. for x in room.x1 + 1 ..= room.x2 {
  49. map[xy_idx(x, y)] = TileType::Floor;
  50. }
  51. }
  52. }
  53. pub fn draw_map(map: &[TileType], ctx : &mut Rltk) {
  54. let mut y = 0;
  55. let mut x = 0;
  56. for tile in map.iter() {
  57. // Render a tile depending upon the tile type
  58. match tile {
  59. TileType::Floor => {
  60. ctx.set(x, y, RGB::from_f32(0.5, 0.5, 0.5), RGB::from_f32(0., 0., 0.), rltk::to_cp437('.'));
  61. }
  62. TileType::Wall => {
  63. ctx.set(x, y, RGB::from_f32(0.0, 1.0, 0.0), RGB::from_f32(0., 0., 0.), rltk::to_cp437('#'));
  64. }
  65. }
  66. // Move the coordinates
  67. x += 1;
  68. if x > 79 {
  69. x = 0;
  70. y += 1;
  71. }
  72. }
  73. }