item module
This commit is contained in:
68
src/item.rs
Normal file
68
src/item.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use crate::{AnimationFrames, Image, mocks};
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub struct Item {
|
||||
pub(crate) id: String,
|
||||
pub(crate) animation_frames: Vec<Image>,
|
||||
pub(crate) name: Option<String>,
|
||||
pub(crate) dialogue: Option<String>, // dialogue id
|
||||
}
|
||||
|
||||
impl From<String> for Item {
|
||||
fn from(string: String) -> Item {
|
||||
let mut lines: Vec<&str> = string.lines().collect();
|
||||
|
||||
let id = lines[0].replace("ITM ", "");
|
||||
let mut name = None;
|
||||
let mut dialogue = None;
|
||||
|
||||
for _ in 0..2 {
|
||||
let last_line = lines.pop().unwrap();
|
||||
|
||||
if last_line.starts_with("NAME") {
|
||||
name = Some(last_line.replace("NAME ", "").to_string());
|
||||
} else if last_line.starts_with("DLG") {
|
||||
dialogue = Some(last_line.replace("DLG ", "").to_string());
|
||||
} else {
|
||||
lines.push(last_line);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// todo dedupe
|
||||
let animation_frames = lines[1..].join("");
|
||||
let animation_frames: Vec<&str> = animation_frames.split("\n>\n").collect();
|
||||
let animation_frames: Vec<Image> = animation_frames.iter().map(|&frame| {
|
||||
Image::from(frame.to_string())
|
||||
}).collect();
|
||||
|
||||
Item { id, name, animation_frames, dialogue }
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for Item {
|
||||
#[inline]
|
||||
fn to_string(&self) -> String {
|
||||
format!(
|
||||
"ITM {}\n{}{}{}",
|
||||
self.id,
|
||||
self.animation_frames.to_string(),
|
||||
if self.name.is_some() { format!("\nNAME {}", self.name.as_ref().unwrap()) } else { "".to_string() },
|
||||
if self.dialogue.is_some() { format!("\nDLG {}", self.dialogue.as_ref().unwrap()) } else { "".to_string() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_item_from_string() {
|
||||
let output = Item::from(include_str!("../test/resources/item").to_string());
|
||||
let expected = mocks::item();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_item_to_string() {
|
||||
let output = mocks::item().to_string();
|
||||
let expected = include_str!("../test/resources/item").to_string();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
Reference in New Issue
Block a user