1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use crate::{AnimationFrames, Image, Position};
use crate::mock;

/// avatar is a "sprite" in the game data but with a specific id
#[derive(Debug, Eq, PartialEq)]
pub struct Avatar {
    pub(crate) animation_frames: Vec<Image>,
    pub(crate) room: String, /// room id
    pub(crate) position: Position,
}

impl From<String> for Avatar {
    fn from(string: String) -> Avatar {
        let string = string.replace("SPR A\n", "");
        let mut lines: Vec<&str> = string.lines().collect();
        let room_pos = lines.pop().unwrap().replace("POS ", "");
        let room_pos: Vec<&str> = room_pos.split_whitespace().collect();
        let room = room_pos[0].to_string();
        let position = Position::from(room_pos[1].to_string());
        let animation_frames: String = lines.join("\n");
        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();

        Avatar { animation_frames, room, position }
    }
}

impl ToString for Avatar {
    #[inline]
    fn to_string(&self) -> String {
        format!(
            "SPR A\n{}\nPOS {} {}",
            self.animation_frames.to_string(),
            self.room,
            self.position.to_string()
        )
    }
}

#[test]
fn test_avatar_from_string() {
    let output = Avatar::from(
        include_str!("../test/resources/avatar").to_string()
    );

    assert_eq!(output, mock::avatar());
}

#[test]
fn test_avatar_to_string() {
    assert_eq!(mock::avatar().to_string(), include_str!("../test/resources/avatar"));
}