Load maps from TOML files with XPM-style palette

Introduces a map file format: TOML with a [palette] mapping characters
to (Glyph, Element) definitions and a [grid] multi-line string. Board
now owns the player position, objects, and portals. map_file::load()
deserializes a file and converts it to a Board via From<MapFile>.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-16 01:50:05 -05:00
parent 37c10c7c38
commit 2dc749e037
6 changed files with 254 additions and 69 deletions
+97
View File
@@ -0,0 +1,97 @@
use std::collections::HashMap;
use serde::Deserialize;
use eframe::egui::Color32;
use crate::game::{Board, Element, Glyph, ObjectDef, Player, PortalDef};
#[derive(Deserialize)]
pub struct MapFile {
pub map: MapHeader,
pub palette: HashMap<String, PaletteEntry>,
pub grid: GridData,
#[serde(default)]
pub objects: Vec<ObjectDef>,
#[serde(default)]
pub portals: Vec<PortalDef>,
}
#[derive(Deserialize)]
pub struct MapHeader {
#[allow(dead_code)]
pub name: String,
pub width: usize,
pub height: usize,
pub player_start: [i32; 2],
}
#[derive(Deserialize)]
pub struct PaletteEntry {
pub passable: bool,
pub ch: char,
pub fg: String,
pub bg: String,
}
#[derive(Deserialize)]
pub struct GridData {
pub content: String,
}
fn parse_color(hex: &str) -> Color32 {
let hex = hex.trim_start_matches('#');
if hex.len() != 6 {
return Color32::BLACK;
}
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
Color32::from_rgb(r, g, b)
}
impl From<MapFile> for Board {
fn from(mf: MapFile) -> Self {
let w = mf.map.width;
let h = mf.map.height;
let mut elements: Vec<Element> = Vec::new();
let mut palette: HashMap<char, (Glyph, usize)> = HashMap::new();
for (key, entry) in &mf.palette {
let key_char = key.chars().next().unwrap_or(' ');
let idx = elements.len();
elements.push(Element { passable: entry.passable });
palette.insert(key_char, (Glyph {
ch: entry.ch,
fg: parse_color(&entry.fg),
bg: parse_color(&entry.bg),
}, idx));
}
let mut cells: Vec<(Glyph, usize)> = Vec::with_capacity(w * h);
for line in mf.grid.content.lines() {
for ch in line.chars() {
if let Some(&(glyph, idx)) = palette.get(&ch) {
cells.push((glyph, idx));
}
}
}
Board {
width: w,
height: h,
elements,
cells,
player: Player {
x: mf.map.player_start[0],
y: mf.map.player_start[1],
},
objects: mf.objects,
portals: mf.portals,
}
}
}
pub fn load(path: &str) -> Result<Board, Box<dyn std::error::Error>> {
let content = std::fs::read_to_string(path)?;
let map_file: MapFile = toml::from_str(&content)?;
Ok(Board::from(map_file))
}