field loader

This commit is contained in:
2026-03-09 20:30:16 -05:00
parent 085c3ab62f
commit 9856fd5f41
8 changed files with 125 additions and 2 deletions

View File

@@ -1,4 +1,4 @@
#[derive(Clone, Copy, PartialEq)] #[derive(Clone, Copy, PartialEq, Debug)]
pub enum Tile { pub enum Tile {
Empty, Empty,
Wall, Wall,

View File

@@ -0,0 +1,5 @@
use crate::field::field::Field;
pub trait FieldLoader {
fn load(field_id: String) -> Field;
}

View File

@@ -0,0 +1,2 @@
pub mod loader;
pub mod plain_text_loader;

View File

@@ -0,0 +1,55 @@
use crate::field::field::{Field, Tile};
use crate::field::loader::loader::FieldLoader;
use std::fs;
pub struct PlainTextFieldLoader;
impl FieldLoader for PlainTextFieldLoader {
fn load(field_id: String) -> Field {
let content = fs::read_to_string(&field_id)
.expect("Could not read field file");
let lines: Vec<&str> = content.lines().collect();
let height = lines.len();
let width = lines.iter().map(|l| l.len()).max().unwrap_or(0);
let mut tiles = vec![Tile::Empty; width * height];
for (y, line) in lines.iter().enumerate() {
for (x, ch) in line.chars().enumerate() {
let tile = match ch {
'x' => Tile::Wall,
_ => Tile::Empty,
};
tiles[y * width + x] = tile;
}
}
Field { width, height, tiles }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_load_from_file() {
let test_file = "test_level_tmp.txt";
let level_data = "xxxx\nx x\nxxxx";
fs::write(test_file, level_data).expect("Could not write test file");
let field = PlainTextFieldLoader::load(test_file.to_string());
let _ = fs::remove_file(test_file);
assert_eq!(field.width, 4);
assert_eq!(field.height, 3);
assert_eq!(field.tiles[0], Tile::Wall);
assert_eq!(field.tiles[5], Tile::Empty);
}
}

View File

@@ -1 +1,2 @@
pub mod field; pub mod field;
pub mod loader;

20
game_data/fields/basic Normal file
View File

@@ -0,0 +1,20 @@
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

20
game_data/fields/maze1 Normal file
View File

@@ -0,0 +1,20 @@
xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx
x x
x x
x xx x
x xx x
x xx x
x xx x
xx
xxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxx
xx
x xx x
x xx x
x xx x
x xx x
x x
x x
x x
x x
xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx

20
game_data/fields/open Normal file
View File

@@ -0,0 +1,20 @@