wraithfate/src/parse_map.rs

54 lines
2.0 KiB
Rust

use std::fs; // For reading the map and save files
use crate::Coordinates;
// This function reads the map file and puts it into a 2d vector of integers, each integer
// Refers to a block (see top comment) and the function returns this vector
pub fn parse_map(player_coordinates: &Coordinates) -> Result<(Vec<Vec<char>>, Vec<Vec<char>>), u8>
{
let mut ground_map: Vec<Vec<char>> = Vec::new(); // Initialises the Ground map vector
let mut above_map: Vec<Vec<char>> = Vec::new(); // Initialises the Above Ground map vector
let ground_file = format!("data/{}_ground.map",player_coordinates.map);
let above_file = format!("data/{}_above.map",player_coordinates.map);
// Read the ground map file
if let Ok(parsed_ground_file_contents) = fs::read_to_string(&ground_file)
{
let ground_file_contents = parsed_ground_file_contents;
let ground_rows = ground_file_contents.split("\n").collect::<Vec<_>>(); // Split the file contents into rows
// Loop over each row to parse each column of it
for row in 0..ground_rows.len()
{
// Turn each column into an integer and collect it into a row vector
let current_row = ground_rows[row].chars().collect();
ground_map.push(current_row); // Then push this vector to the full map vector
}
}
else
{
eprintln!("Error: Could not read file: {}", ground_file);
return Err(1)
}
// Read the above ground map file
if let Ok(parsed_above_file_contents) = fs::read_to_string(&above_file)
{
let above_file_contents = parsed_above_file_contents;
let above_rows = above_file_contents.split("\n").collect::<Vec<_>>(); // Split the file contents into rows
// Loop over each row to parse each column of it
for row in 0..above_rows.len()
{
// Turn each column into an integer and collect it into a row vector
let current_row = above_rows[row].chars().collect();
above_map.push(current_row); // Then push this vector to the full map vector
}
}
else
{
eprintln!("Error: Could not read file: {}", ground_file);
return Err(1)
}
return Ok((ground_map, above_map))
}