環境
- Time 2022-11-30
- WSL-Ubuntu 22.04
- RLTK 0.8.7
前言
說明
參考:https://bfnightly.bracketproductions.com/rustbook
目標
基於前一節的內容,不渲染整個大地圖,而只渲染角色周圍的可視區。
重構地圖結構
#[derive(Default)]
pub struct Map {
pub tiles: Vec<TileType>,
pub rooms: Vec<Rect>,
pub width: i32,
pub height: i32,
}
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,
};
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)
}
}
Component
use rltk::{field_of_view, Point, RGB};
use specs::prelude::*;
use specs_derive::Component;
use crate::map::Map;
#[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 struct VisibilitySystem {}
impl<'a> System<'a> for VisibilitySystem {
type SystemData = (
ReadExpect<'a, Map>,
WriteStorage<'a, Viewshed>,
WriteStorage<'a, Point>,
);
fn run(&mut self, data: Self::SystemData) {
let (map, mut views, pos) = data;
for (views, pos) in (&mut views, &pos).join() {
views.visible_tiles.clear();
views.visible_tiles = field_of_view(Point::new(pos.x, pos.y), views.range, &*map);
views
.visible_tiles
.retain(|p| p.x >= 0 && p.x < map.width && p.y >= 0 && p.y < map.height);
}
}
}
渲染可視區地圖
pub fn draw_map(world: &World, ctx: &mut Rltk) {
let mut viewsheds = world.write_storage::<Viewshed>();
let mut players = world.write_storage::<Player>();
let map = world.fetch::<Map>();
for (_player, viewshed) in (&mut players, &mut viewsheds).join() {
let mut y = 0;
let mut x = 0;
for tile in map.tiles.iter() {
let pt = Point::new(x, y);
if viewshed.visible_tiles.contains(&pt) {
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;
}
}
}
}
main
use comp::{Player, Renderable, Viewshed, VisibilitySystem};
use map::Map;
use rltk::prelude::*;
use specs::prelude::*;
mod comp;
mod map;
mod player;
pub struct State {
world: World,
}
impl GameState for State {
fn tick(&mut self, context: &mut Rltk) {
context.cls();
player::player_input(self, context);
self.run_systems();
map::draw_map(&self.world, context);
let positions = self.world.read_storage::<Point>();
let renderables = self.world.read_storage::<Renderable>();
for (pos, render) in (&positions, &renderables).join() {
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);
self.world.maintain();
}
}
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::<Player>();
state.world.register::<Viewshed>();
let map = Map::new_map();
let point = map.rooms[0].center();
state.world.insert(map);
state
.world
.create_entity()
.with(point)
.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,
})
.build();
rltk::main_loop(context, state)
}
效果
總結
只渲染角色周圍一部分的視野。