From b9dac0932f9ff85ff468a9b8d2665b1d2badccad Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Mon, 13 Apr 2020 19:08:21 +0100 Subject: [PATCH] function for optional lines of game data --- src/lib.rs | 16 ++++++++++++++++ src/sprite.rs | 16 +++++++++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 301e8b7..fce01f9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,6 +30,7 @@ use room::Room; use sprite::Sprite; use tile::Tile; use variable::Variable; +use std::fmt::Display; #[derive(Debug, Eq, PartialEq)] pub struct Instance { @@ -95,3 +96,18 @@ impl ToBase36 for u64 { fn test_to_base36() { assert_eq!((37 as u64).to_base36(), "11"); } + +/// e.g. `\nNAME DLG_0` +fn optional_data_line(label: &str, item: Option) -> String { + if item.is_some() { + format!("\n{} {}", label, item.unwrap()) + } else { + "".to_string() + } +} + +#[test] +fn test_optional_data_line() { + let output = optional_data_line("NAME", mock::item().name); + assert_eq!(output, "\nNAME door".to_string()); +} diff --git a/src/sprite.rs b/src/sprite.rs index 44df374..19cd59c 100644 --- a/src/sprite.rs +++ b/src/sprite.rs @@ -1,4 +1,4 @@ -use crate::{AnimationFrames, Image, Position, mock, from_base36, ToBase36}; +use crate::{AnimationFrames, Image, Position, mock, from_base36, ToBase36, optional_data_line}; #[derive(Debug, Eq, PartialEq)] pub struct Sprite { @@ -10,6 +10,16 @@ pub struct Sprite { pub position: Position, } +impl Sprite { + fn name_line(&self) -> String { + optional_data_line("NAME", self.name.as_ref()) + } + + fn dialogue_line(&self) -> String { + optional_data_line("DLG", self.dialogue_id.as_ref()) + } +} + impl From for Sprite { fn from(string: String) -> Sprite { let mut lines: Vec<&str> = string.lines().collect(); @@ -59,8 +69,8 @@ impl ToString for Sprite { "SPR {}\n{}{}{}\nPOS {} {}", self.id.to_base36(), self.animation_frames.to_string(), - if self.name.as_ref().is_some() { format!("\nNAME {}", self.name.as_ref().unwrap()) } else { "".to_string() }, - if self.dialogue_id.as_ref().is_some() { format!("\nDLG {}", self.dialogue_id.as_ref().unwrap()) } else { "".to_string() }, + self.name_line(), + self.dialogue_line(), self.room_id.to_base36(), self.position.to_string(), )