summaryrefslogtreecommitdiff
path: root/src/map.rs
blob: ed90f1a26f5e7f5bb9dc3d33d3945986904b7ecd (plain)
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
use ggez::filesystem::File;
use std::io::BufReader;
use xml::reader::{EventReader, XmlEvent};

pub struct Map {
    pub width: usize,
    pub height: usize,
    pub layers: Vec<Layer>,
}

impl Map {
    pub fn new(file: File) -> Map {
        let mut width = None;
        let mut height = None;
        let mut layers = Vec::new();

        for e in EventReader::new(BufReader::new(file)) {
            if let Ok(XmlEvent::StartElement {
                name, attributes, ..
            }) = e
            {
                if name.local_name == "map" {
                    for attribute in attributes {
                        match attribute.name.local_name.as_str() {
                            "width" => width = Some(attribute.value.parse::<usize>().unwrap()),
                            "height" => height = Some(attribute.value.parse::<usize>().unwrap()),
                            _ => (),
                        }
                    }
                }
            } else if let Ok(XmlEvent::Characters(text)) = e {
                layers.push(Layer::new(text));
            }
        }

        Map {
            layers,
            width: width.unwrap(),
            height: height.unwrap(),
        }
    }
}

pub struct Layer {
    pub data: Vec<usize>,
}

impl Layer {
    pub fn new(text: String) -> Layer {
        Layer {
            data: text
                .replace("\n", "")
                .split(',')
                .map(|s| s.parse().unwrap())
                .collect(),
        }
    }
}