首页 > 其他分享 >0244-RLTK-增加地图怪物

0244-RLTK-增加地图怪物

时间:2024-08-19 10:07:17浏览次数:11  
标签:RLTK 0244 mut self pub map let 怪物 world

环境

  • 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)
}

效果

增加怪物

总结

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

附录

标签:RLTK,0244,mut,self,pub,map,let,怪物,world
From: https://www.cnblogs.com/jiangbo4444/p/18366769

相关文章

  • Unity 麦扣 x 勇士传说 全解析 之 怪物基类与野猪(附各模块知识的链接,零基础也包学会的
    通过一阵子的学习,我是这么认为的,因为该教程是难度两星的教程 ,也就是适合学了一阵子基础组件以后的学习者(什么都不会的学习者要是学这套课程会困难重重,如果你什么都不会那么需要学习一星教程)所以该课程没有那么多manger,代码也不那么面向对象,但是从怪物类之后就开始有相关的内......
  • 0236-RLTK-渲染动态字符
    环境Time2022-11-29WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook目标在前一节的基础上,将静止的字符进行移动。Component#[derive(Component)]structPosition{x:i32,y:i32,}#[derive(Component)]st......
  • 0237-RLTK-控制角色移动
    环境Time2022-11-29WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook目标使用键盘来控制角色在窗口中进行移动。Component#[derive(Component)]structPosition{x:i32,y:i32,}#[derive(Component)]struc......
  • 0238-RLTK-生成大地图
    环境Time2022-11-29WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook目标基于前一节的内容,生成一张可以让角色移动的大地图。地板和墙#[derive(PartialEq,Copy,Clone)]enumTileType{Wall,Floor}计算坐标pub......
  • 0239-RLTK-分割不同文件
    环境Time2022-11-30WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook目标基于前一节的内容,随着main.rs文件中的内容越来越多,将其进行分割。comp.rsuserltk::RGB;usespecs::prelude::*;usespecs_derive::Component;......
  • 0240-RLTK-生成小房间
    环境Time2022-11-30WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook目标基于前一节的内容,生成两个小房间,只修改map.rs文件。生成房间函数fnapply_room_to_map(room:&Rect,map:&mut[TileType]){foryinroom......
  • 0234-RLTK-创建主程序窗口
    环境Time2022-11-29WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook/chapter_1.html目标RLTK表示RoguelikeToolkit,随机游戏工具包,使用这个包创建一个主窗口。Cargo.toml[package]edition="2021"name="game"vers......
  • 0235-RLTK-渲染静态字符
    环境Time2022-11-29WSL-Ubuntu22.04RLTK0.8.7前言说明参考:https://bfnightly.bracketproductions.com/rustbook/目标渲染一个主窗口,并且在窗口上渲染一些静态的字符。Cargo.toml[package]edition="2021"name="game"version="0.1.0"[dependencies]rl......
  • WindowsUpdate 更新错误 0x80244018
     更新windows的时候遇到了下载进度始终0%的问题,在网上检索了好多办法,最后在这个回答下(WindowsUpdate更新错误0x80244018-MicrosoftCommunity)解决了这次问题。   当提醒重启计算机的时候,重启,同时会显示正在更新。开机后我的电脑显示已经更新到最新版本。 ......
  • Monsters Pack 04(游戏卡通可爱怪兽怪物战士模型)
    以下模型有3种进化形态:捕手战士鱼卫战士骑士战士小鬼战士猴东战士无鼻战士坑娃战士刺头战士树斯特战士楔形战士这些模型是为您的主要角色设计的敌人。进化的每个阶段都会使他变得更加强大,因此您可以用它来增强对手的实力,并作为敌人的boss。它适用于不同类型的游戏......