0241-RLTK-连接小房间
环境
- Time 2022-11-30
- WSL-Ubuntu 22.04
- RLTK 0.8.7
前言
说明
参考:https://bfnightly.bracketproductions.com/rustbook
目标
基于前一节的内容,生成多个小房间,并且连接它们,增加控制方式。
水平通道
fn horizontal_tunnel(map: &mut [TileType], x1: i32, x2: i32, y: i32) {
for x in min(x1, x2)..=max(x1, x2) {
let idx = index(x, y);
if idx > 0 && idx < 80 * 50 {
map[idx as usize] = TileType::Floor;
}
}
}
垂直通道
fn vertical_tunnel(map: &mut [TileType], y1: i32, y2: i32, x: i32) {
for y in min(y1, y2)..=max(y1, y2) {
let idx = index(x, y);
if idx > 0 && idx < 80 * 50 {
map[idx as usize] = TileType::Floor;
}
}
}
生成地图
const MAX_ROOMS: i32 = 30;
const MIN_SIZE: i32 = 6;
const MAX_SIZE: i32 = 10;
pub fn new_map() -> (Vec<Rect>, Vec<TileType>) {
let mut map = vec![TileType::Wall; 80 * 50];
let mut rooms: Vec<Rect> = Vec::new();
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, 80 - w - 1) - 1;
let y = rng.roll_dice(1, 50 - h - 1) - 1;
let new_room = Rect::with_size(x, y, w, h);
let mut ok = true;
for other_room in rooms.iter() {
if new_room.intersect(other_room) {
ok = false
}
}
if ok {
apply_room(&new_room, &mut map);
if !rooms.is_empty() {
let cur = new_room.center();
let pre = rooms[rooms.len() - 1].center();
if rng.range(0, 2) == 1 {
horizontal_tunnel(&mut map, pre.x, cur.x, pre.y);
vertical_tunnel(&mut map, pre.y, cur.y, cur.x);
} else {
vertical_tunnel(&mut map, pre.y, cur.y, pre.x);
horizontal_tunnel(&mut map, pre.x, cur.x, cur.y);
}
}
rooms.push(new_room);
}
}
(rooms, map)
}
新增控制方式
pub fn player_input(state: &mut State, context: &mut Rltk) {
if let Some(key) = context.key {
match key {
VirtualKeyCode::Left | VirtualKeyCode::Numpad4 | VirtualKeyCode::H => {
move_player(-1, 0, &mut state.world)
}
VirtualKeyCode::Right | VirtualKeyCode::Numpad6 | VirtualKeyCode::L => {
move_player(1, 0, &mut state.world)
}
VirtualKeyCode::Up | VirtualKeyCode::Numpad8 | VirtualKeyCode::K => {
move_player(0, -1, &mut state.world)
}
VirtualKeyCode::Down | VirtualKeyCode::Numpad2 | VirtualKeyCode::J => {
move_player(0, 1, &mut state.world)
}
_ => {}
}
}
}
放置角色
fn main() -> rltk::BError {
let context = rltk::RltkBuilder::simple80x50()
.with_title("冒险游戏")
.build()?;
let mut state = State {
world: World::new(),
};
state.world.register::<Point>();
state.world.register::<Renderable>();
state.world.register::<LeftWalker>();
state.world.register::<Player>();
let (rooms, map) = map::new_map();
state.world.insert(map);
state
.world
.create_entity()
.with(rooms[0].center())
.with(Renderable {
glyph: rltk::to_cp437('@'),
fg: RGB::named(rltk::YELLOW),
bg: RGB::named(rltk::BLACK),
})
.with(Player {})
.build();
rltk::main_loop(context, state)
}
效果
总结
生成多个小房间,将它们连接起来,新增控制方式,可以通过 vim 的方式和数字键盘。