环境
- Time 2022-11-29
- WSL-Ubuntu 22.04
- RLTK 0.8.7
前言
说明
参考:https://bfnightly.bracketproductions.com/rustbook
目标
基于前一节的内容,生成一张可以让角色移动的大地图。
地板和墙
#[derive(PartialEq, Copy, Clone)]
enum TileType {
Wall, Floor
}
计算坐标
pub fn index(x: i32, y: i32) -> usize {
(y as usize * 80) + x as usize
}
生成地图
fn new_map() -> Vec<TileType> {
let mut map = vec![TileType::Floor; 80 * 50];
for x in 0..80 {
map[index(x, 0)] = TileType::Wall;
map[index(x, 49)] = TileType::Wall;
}
for y in 0..50 {
map[index(0, y)] = TileType::Wall;
map[index(79, y)] = TileType::Wall;
}
let mut rng = rltk::RandomNumberGenerator::new();
for _i in 0..400 {
let x = rng.roll_dice(1, 79);
let y = rng.roll_dice(1, 49);
let idx = index(x, y);
if idx != index(40, 25) {
map[idx] = TileType::Wall;
}
}
map
}
绘制地图
fn draw_map(map: &[TileType], ctx: &mut Rltk) {
let mut y = 0;
let mut x = 0;
for tile in map.iter() {
match tile {
TileType::Floor => {
ctx.set(
x,
y,
RGB::from_f32(0.5, 0.5, 0.5),
RGB::from_f32(0., 0., 0.),
rltk::to_cp437('.'),
);
}
TileType::Wall => {
ctx.set(
x,
y,
RGB::from_f32(0.0, 1.0, 0.0),
RGB::from_f32(0., 0., 0.),
rltk::to_cp437('#'),
);
}
}
x += 1;
if x > 79 {
x = 0;
y += 1;
}
}
}
墙壁碰撞
fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
let mut positions = ecs.write_storage::<Position>();
let mut players = ecs.write_storage::<Player>();
let map = ecs.fetch::<Vec<TileType>>();
for (_player, pos) in (&mut players, &mut positions).join() {
let destination_idx = xy_idx(pos.x + delta_x, pos.y + delta_y);
if map[destination_idx] != TileType::Wall {
pos.x = min(79 , max(0, pos.x + delta_x));
pos.y = min(49, max(0, pos.y + delta_y));
}
}
}
GameState
impl GameState for State {
fn tick(&mut self, ctx: &mut Rltk) {
ctx.cls();
player_input(self, ctx);
self.run_systems();
let map = self.world.fetch::<Vec<TileType>>();
draw_map(&map, ctx);
let positions = self.world.read_storage::<Position>();
let renderables = self.world.read_storage::<Renderable>();
for (pos, render) in (&positions, &renderables).join() {
ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph);
}
}
}
main
fn main() -> rltk::BError {
let context = rltk::RltkBuilder::simple80x50()
.with_title("冒险游戏")
.build()?;
let mut state = State {
world: World::new(),
};
state.world.register::<Position>();
state.world.register::<Renderable>();
state.world.register::<LeftWalker>();
state.world.register::<Player>();
state.world.insert(new_map());
state
.world
.create_entity()
.with(Position { x: 40, y: 25 })
.with(Renderable {
glyph: rltk::to_cp437('@'),
fg: RGB::named(rltk::YELLOW),
bg: RGB::named(rltk::BLACK),
})
.with(Player {})
.build();
rltk::main_loop(context, state)
}
效果
总结
生成一张大地图,角色可以在除了墙的地方行走。