0244-RLTK-增加地图怪物

环境

  • Time 2022-12-01
  • WSL-Ubuntu 22.04
  • RLTK 0.8.7

前言

说明

参考:https://bfnightly.bracketproductions.com/rustbook

目标

基于前一节的内容,在每个房间的中间放置怪物。

comp.rs

use rltk::{console, field_of_view, Point, RGB};
use specs::prelude::*;
use specs_derive::Component;

use crate::map::Map;

#[derive(Component)]
pub struct Position {
    pub x: i32,
    pub y: i32,
}

#[derive(Component)]
pub struct Renderable {
    pub glyph: rltk::FontCharType,
    pub fg: RGB,
    pub bg: RGB,
}

#[derive(Component, Debug)]
pub struct Player {}

#[derive(Component)]
pub struct Viewshed {
    pub visible_tiles: Vec<rltk::Point>,
    pub range: i32,
    pub dirty: bool,
}

pub struct VisibilitySystem {}

impl<'a> System<'a> for VisibilitySystem {
    type SystemData = (
        WriteExpect<'a, Map>,
        Entities<'a>,
        WriteStorage<'a, Viewshed>,
        WriteStorage<'a, Position>,
        ReadStorage<'a, Player>,
    );

    fn run(&mut self, data: Self::SystemData) {
        let (mut map, entities, mut viewshed, pos, player) = data;

        for (ent, viewshed, pos) in (&entities, &mut viewshed, &pos).join() {
            if viewshed.dirty {
                viewshed.dirty = false;
                viewshed.visible_tiles.clear();
                viewshed.visible_tiles =
                    field_of_view(Point::new(pos.x, pos.y), viewshed.range, &*map);
                viewshed
                    .visible_tiles
                    .retain(|p| p.x >= 0 && p.x < map.width && p.y >= 0 && p.y < map.height);

                let _p: Option<&Player> = player.get(ent);
                if let Some(_p) = _p {
                    for t in map.visible.iter_mut() {
                        *t = false
                    }
                    for vis in viewshed.visible_tiles.iter() {
                        let idx = map.index(vis.x, vis.y);
                        map.revealed[idx] = true;
                        map.visible[idx] = true;
                    }
                }
            }
        }
    }
}

#[derive(Component, Debug)]
pub struct Monster {}

pub struct MonsterAI {}

impl<'a> System<'a> for MonsterAI {
    type SystemData = (
        ReadExpect<'a, Point>,
        ReadStorage<'a, Viewshed>,
        ReadStorage<'a, Monster>,
        ReadStorage<'a, Name>,
    );

    fn run(&mut self, data: Self::SystemData) {
        let (player_pos, viewshed, monster, name) = data;

        for (viewshed, _monster, name) in (&viewshed, &monster, &name).join() {
            if viewshed.visible_tiles.contains(&*player_pos) {
                console::log(&format!("{} shouts insults", name.name));
            }
        }
    }
}

#[derive(Component, Debug)]
pub struct Name {
    pub name: String,
}

player.rs

use crate::comp::{Player, Position, Viewshed};
use crate::map::{Map, TileType};
use crate::{RunState, State};
use rltk::prelude::*;
use specs::{Join, World, WorldExt};
use std::cmp::{max, min};

pub fn move_player(delta_x: i32, delta_y: i32, world: &mut World) {
    let mut positions = world.write_storage::<Position>();
    let mut players = world.write_storage::<Player>();
    let mut viewsheds = world.write_storage::<Viewshed>();
    let map = world.fetch::<Map>();
    for (_player, pos, viewshed) in (&mut players, &mut positions, &mut viewsheds).join() {
        let destination_idx = map.index(pos.x + delta_x, pos.y + delta_y);
        if map.tiles[destination_idx] != TileType::Wall {
            pos.x = min(79, max(0, pos.x + delta_x));
            pos.y = min(49, max(0, pos.y + delta_y));

            viewshed.dirty = true;
            let mut ppos = world.write_resource::<Point>();
            ppos.x = pos.x;
            ppos.y = pos.y;
        }
    }
}

pub fn player_input(state: &mut State, context: &mut Rltk) -> RunState {
    match context.key {
        None => return RunState::Paused,
        Some(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)
            }

            _ => return RunState::Paused,
        },
    }
    RunState::Running
}

map.rs

use rltk::prelude::*;
use specs::prelude::*;
use std::cmp::{max, min};

#[derive(PartialEq, Eq, Copy, Clone)]
pub enum TileType {
    Wall,
    Floor,
}

#[derive(Default)]
pub struct Map {
    pub tiles: Vec<TileType>,
    pub rooms: Vec<Rect>,
    pub width: i32,
    pub height: i32,
    pub revealed: Vec<bool>,
    pub visible: Vec<bool>,
}

impl Map {
    pub fn index(&self, x: i32, y: i32) -> usize {
        (y as usize * self.width as usize) + x as usize
    }

    pub fn new_map() -> Map {
        let mut map = Map {
            tiles: vec![TileType::Wall; 80 * 50],
            rooms: Vec::new(),
            width: 80,
            height: 50,
            revealed: vec![false; 80 * 50],
            visible: vec![false; 80 * 50],
        };
        let mut rng = RandomNumberGenerator::new();

        const MAX_ROOMS: i32 = 30;
        const MIN_SIZE: i32 = 6;
        const MAX_SIZE: i32 = 10;

        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 map.rooms.iter() {
                if new_room.intersect(other_room) {
                    ok = false
                }
            }
            if ok {
                map.apply_room(&new_room);

                if !map.rooms.is_empty() {
                    let cur = new_room.center();
                    let pre = map.rooms[map.rooms.len() - 1].center();
                    if rng.range(0, 2) == 1 {
                        map.horizontal_tunnel(pre.x, cur.x, pre.y);
                        map.vertical_tunnel(pre.y, cur.y, cur.x);
                    } else {
                        map.vertical_tunnel(pre.y, cur.y, pre.x);
                        map.horizontal_tunnel(pre.x, cur.x, cur.y);
                    }
                }

                map.rooms.push(new_room);
            }
        }

        map
    }

    fn apply_room(&mut self, room: &Rect) {
        for y in room.y1 + 1..=room.y2 {
            for x in room.x1 + 1..=room.x2 {
                let index = self.index(x, y);
                self.tiles[index] = TileType::Floor;
            }
        }
    }

    fn horizontal_tunnel(&mut self, x1: i32, x2: i32, y: i32) {
        for x in min(x1, x2)..=max(x1, x2) {
            let idx = self.index(x, y);
            if idx > 0 && idx < self.width as usize * self.height as usize {
                self.tiles[idx as usize] = TileType::Floor;
            }
        }
    }

    fn vertical_tunnel(&mut self, y1: i32, y2: i32, x: i32) {
        for y in min(y1, y2)..=max(y1, y2) {
            let idx = self.index(x, y);
            if idx > 0 && idx < 80 * 50 {
                self.tiles[idx as usize] = TileType::Floor;
            }
        }
    }
}

impl BaseMap for Map {
    fn is_opaque(&self, idx: usize) -> bool {
        self.tiles[idx as usize] == TileType::Wall
    }
}

impl Algorithm2D for Map {
    fn dimensions(&self) -> Point {
        Point::new(self.width, self.height)
    }
}

pub fn draw_map(world: &World, ctx: &mut Rltk) {
    let map = world.fetch::<Map>();

    let mut y = 0;
    let mut x = 0;
    for (idx, tile) in map.tiles.iter().enumerate() {
        // Render a tile depending upon the tile type

        if map.revealed[idx] {
            let glyph;
            let mut fg;
            match tile {
                TileType::Floor => {
                    glyph = rltk::to_cp437('.');
                    fg = RGB::from_f32(0.0, 0.5, 0.5);
                }
                TileType::Wall => {
                    glyph = rltk::to_cp437('#');
                    fg = RGB::from_f32(0., 1.0, 0.);
                }
            }
            if !map.visible[idx] {
                fg = fg.to_greyscale()
            }
            ctx.set(x, y, fg, RGB::from_f32(0., 0., 0.), glyph);
        }

        x += 1;
        if x > 79 {
            x = 0;
            y += 1;
        }
    }
}

main.rs

use comp::{Monster, MonsterAI, Name, Player, Position, Renderable, Viewshed, VisibilitySystem};
use map::Map;
use player::player_input;
use rltk::prelude::*;
use specs::prelude::*;

mod comp;
mod map;
mod player;

pub struct State {
    world: World,
    pub runstate: RunState,
}
impl GameState for State {
    fn tick(&mut self, context: &mut Rltk) {
        context.cls();

        if self.runstate == RunState::Running {
            self.run_systems();
            self.runstate = RunState::Paused;
        } else {
            self.runstate = player_input(self, context);
        }

        map::draw_map(&self.world, context);
        let map = self.world.fetch::<Map>();

        let positions = self.world.read_storage::<Position>();
        let renderables = self.world.read_storage::<Renderable>();
        for (pos, render) in (&positions, &renderables).join() {
            let index = map.index(pos.x, pos.y);
            if map.visible[index] {
                context.set(pos.x, pos.y, render.fg, render.bg, render.glyph);
            }
        }
    }
}

impl State {
    fn run_systems(&mut self) {
        let mut vis = VisibilitySystem {};
        vis.run_now(&self.world);

        let mut mob = MonsterAI {};
        mob.run_now(&self.world);
        self.world.maintain();
    }
}

#[derive(PartialEq, Eq, Copy, Clone)]
pub enum RunState {
    Paused,
    Running,
}

fn main() -> rltk::BError {
    let context = rltk::RltkBuilder::simple80x50()
        .with_title("冒险游戏")
        .build()?;

    let mut state = State {
        runstate: RunState::Running,
        world: World::new(),
    };
    state.world.register::<Position>();
    state.world.register::<Renderable>();
    state.world.register::<Player>();
    state.world.register::<Viewshed>();
    state.world.register::<Monster>();
    state.world.register::<Point>();
    state.world.register::<Name>();

    let map = Map::new_map();
    let mut rng = rltk::RandomNumberGenerator::new();

    for (i, room) in map.rooms.iter().skip(1).enumerate() {
        let (glyph, name) = match rng.roll_dice(1, 2) {
            1 => (rltk::to_cp437('g'), "Goblin"),
            _ => (rltk::to_cp437('o'), "Orc"),
        };
        state
            .world
            .create_entity()
            .with(Position {
                x: room.center().x,
                y: room.center().y,
            })
            .with(Renderable {
                glyph,
                fg: RGB::named(rltk::RED),
                bg: RGB::named(rltk::BLACK),
            })
            .with(Viewshed {
                visible_tiles: Vec::new(),
                range: 8,
                dirty: true,
            })
            .with(Monster {})
            .with(Name {
                name: format!("{} #{}", &name, i),
            })
            .build();
    }

    let point = map.rooms[0].center();
    state.world.insert(map);

    state
        .world
        .create_entity()
        .with(Position {
            x: point.x,
            y: point.y,
        })
        .with(Renderable {
            glyph: rltk::to_cp437('@'),
            fg: RGB::named(rltk::YELLOW),
            bg: RGB::named(rltk::BLACK),
        })
        .with(Player {})
        .with(Viewshed {
            visible_tiles: Vec::new(),
            range: 8,
            dirty: true,
        })
        .with(Name {
            name: "Player".to_string(),
        })
        .build();

    state.world.insert(point);

    rltk::main_loop(context, state)
}

效果

增加怪物

总结

实现了渲染地图的怪物,并且可以检测到角色的靠近。
感觉当前系列理解不是很深刻,有直接抄代码的趋势,先暂停,后面再看。

附录

posted @ 2024-08-19 09:59  jiangbo4444  阅读(9)  评论(0编辑  收藏  举报