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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use crate::{AnimationFrames, Image, Position, optional_data_line, ToBase36, from_base36};

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

impl Avatar {
    fn room_position_line(&self) -> String {
        format!("\nPOS {} {}", self.room_id.to_base36(), self.position.to_string())
    }

    fn colour_line(&self) -> String {
        optional_data_line("COL", self.colour_id.as_ref())
    }
}

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 mut room_id: Option<u64> = None;
        let mut position: Option<Position> = None;
        let mut colour_id: Option<u64> = None;

        loop {
            let last_line = lines.pop().unwrap();

            if last_line.starts_with("POS") {
                let room_pos = last_line.replace("POS ", "");
                let room_pos: Vec<&str> = room_pos.split_whitespace().collect();
                room_id = Some(from_base36(room_pos[0]));

                if room_pos.len() < 2 {
                    panic!("Bad room/position for avatar: {}", string);
                }

                position = Some(Position::from(room_pos[1].to_string()));
            } else if last_line.starts_with("COL") {
                colour_id = Some(last_line.replace("COL ", "").parse().unwrap());
            } else {
                lines.push(last_line);
                break;
            }
        }

        let room_id = room_id.unwrap();
        let position = position.unwrap();

        let animation_frames: String = lines.join("\n");
        let animation_frames: Vec<&str> = animation_frames.split(">").collect();
        let animation_frames: Vec<Image> = animation_frames.iter().map(|&frame| {
            Image::from(frame.to_string())
        }).collect();

        Avatar { animation_frames, room_id, position , colour_id }
    }
}

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

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

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

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