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
90
91
92
93
use crate::AnimationFrames;
use crate::image::Image;
use crate::mock;

#[derive(Debug, Eq, PartialEq)]
pub struct Tile {
    pub id: String, // base36 string
    pub name: Option<String>,
    pub wall: bool,
    pub animation_frames: Vec<Image>,
}

impl From<String> for Tile {
    fn from(string: String) -> Tile {
        let mut lines: Vec<&str> = string.lines().collect();

        let id = lines[0].replace("TIL ", "");

        let last_line = lines.pop().unwrap();
        let wall = match last_line == "WAL true" {
            true => true,
            false => {
                lines.push(last_line);
                false
            }
        };

        let last_line = lines.pop().unwrap();
        let name = match last_line.starts_with("NAME") {
            true => Some(last_line.replace("NAME ", "").to_string()),
            false => {
                lines.push(last_line);
                None
            }
        };

        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();

        Tile { id, name, wall, animation_frames }
    }
}

impl ToString for Tile {
    #[inline]
    fn to_string(&self) -> String {
        format!(
            "TIL {}\n{}{}{}",
            self.id,
            self.animation_frames.to_string(),
            if self.name.as_ref().is_some() { format!("\nNAME {}", self.name.as_ref().unwrap())} else {"".to_string() },
            if self.wall {"\nWAL true"} else {""}
        )
    }
}

#[test]
fn test_tile_from_string() {
    let output = Tile::from(include_str!("../test/resources/tile").to_string());

    let expected = Tile {
        id: "z".to_string(),
        name: Some("concrete 1".to_string()),
        wall: true,
        animation_frames: vec![
            Image {
                pixels: vec![1; 64]
            }
        ],
    };

    assert_eq!(output, expected);
}

#[test]
fn test_tile_to_string() {
    let output = Tile {
        id: "7a".to_string(),
        name: Some("chequers".to_string()),
        wall: false,
        animation_frames: vec![
            mock::image::chequers_1(),
            mock::image::chequers_2(),
        ]
    }.to_string();

    let expected = include_str!("../test/resources/tile-chequers").to_string();

    assert_eq!(output, expected);
}