Add basic map

This commit is contained in:
2022-01-29 16:35:10 +01:00
parent 7c67291031
commit 0af23af3d3
8 changed files with 165 additions and 86 deletions

View File

@@ -0,0 +1,31 @@
use std::cmp::{max, min};
use crate::rect::Rect;
use crate::{Map, TileType};
pub fn apply_room_to_map(map: &mut Map, room: &Rect) {
for y in room.y1 + 1..=room.y2 {
for x in room.x1 + 1..=room.x2 {
let idx = map.xy_idx(x, y);
map.tiles[idx] = TileType::Floor;
}
}
}
pub fn apply_horizontal_tunnel(map: &mut Map, x1: i32, x2: i32, y: i32) {
for x in min(x1, x2)..=max(x1, x2) {
let idx = map.xy_idx(x, y);
if idx > 0 && idx < map.width as usize * map.height as usize {
map.tiles[idx as usize] = TileType::Floor;
}
}
}
pub fn apply_vertical_tunnel(map: &mut Map, y1: i32, y2: i32, x: i32) {
for y in min(y1, y2)..=max(y1, y2) {
let idx = map.xy_idx(x, y);
if idx > 0 && idx < map.width as usize * map.height as usize {
map.tiles[idx as usize] = TileType::Floor;
}
}
}

13
src/map_builders/mod.rs Normal file
View File

@@ -0,0 +1,13 @@
use crate::map_builders::simple_map::SimpleMapBuilder;
use crate::Map;
mod common;
mod simple_map;
trait MapBuilder {
fn build(new_depth: i32) -> Map;
}
pub fn build_random_map(new_depth: i32) -> Map {
SimpleMapBuilder::build(new_depth)
}

View File

@@ -0,0 +1,61 @@
use rltk::RandomNumberGenerator;
use specs::prelude::*;
use crate::map_builders::{common, MapBuilder};
use crate::rect::Rect;
use crate::{Map, TileType};
pub struct SimpleMapBuilder {}
impl SimpleMapBuilder {
fn rooms_and_corridors(map: &mut Map) {
const MAX_ROOMS: i32 = 30;
const MIN_SIZE: i32 = 6;
const MAX_SIZE: i32 = 10;
let mut rng = RandomNumberGenerator::new();
for _ in 0..MAX_ROOMS {
let w = rng.range(MIN_SIZE, MAX_SIZE);
let h = rng.range(MIN_SIZE, MAX_SIZE);
let x = rng.roll_dice(1, map.width - w - 1) - 1;
let y = rng.roll_dice(1, map.height - h - 1) - 1;
let new_room = Rect::new(x, y, w, h);
let mut ok = true;
for other_room in map.rooms.iter() {
if new_room.intersect(other_room) {
ok = false
};
}
if ok {
common::apply_room_to_map(map, &new_room);
if !map.rooms.is_empty() {
let (new_x, new_y) = new_room.center();
let (prev_x, prev_y) = map.rooms[map.rooms.len() - 1].center();
if rng.range(0, 2) == 1 {
common::apply_horizontal_tunnel(map, prev_x, new_x, prev_y);
common::apply_vertical_tunnel(map, prev_y, new_y, new_x);
} else {
common::apply_vertical_tunnel(map, prev_y, new_y, prev_x);
common::apply_horizontal_tunnel(map, prev_x, new_x, new_y);
}
}
map.rooms.push(new_room);
}
}
let stairs_position = map.rooms[map.rooms.len() - 1].center();
let stairs_idx = map.xy_idx(stairs_position.0, stairs_position.1);
map.tiles[stairs_idx] = TileType::DownStairs;
}
}
impl MapBuilder for SimpleMapBuilder {
fn build(new_depth: i32) -> Map {
let mut map = Map::new(new_depth);
SimpleMapBuilder::rooms_and_corridors(&mut map);
map
}
}