summaryrefslogtreecommitdiff
path: root/src/map.rs
blob: fe512423854512af5dffa69eb5f856ec14901ce5 (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
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
94
95
96
97
use ggez::filesystem::File;
use ggez::graphics::spritebatch::SpriteBatch;
use ggez::nalgebra::Point2;
use xml::reader::XmlEvent::Characters;

use crate::constants;
use crate::layer::Layer;
use crate::tileset::Tileset;
use crate::xmlelements::XMLElements;

#[derive(Clone)]
pub struct Map {
    width: usize,
    height: usize,
    layers: Vec<Layer>,
    spawns: Vec<(String, Point2<f32>)>,
}

impl Map {
    pub fn new(file: File, tileset: &Tileset) -> Map {
        let elements = XMLElements::new(file);

        let width = elements
            .get_element_attribute("map", "width")
            .unwrap()
            .parse()
            .unwrap();
        let height = elements
            .get_element_attribute("map", "height")
            .unwrap()
            .parse()
            .unwrap();

        let layers: Vec<Layer> = elements
            .events
            .iter()
            .filter_map(|e| {
                if let Characters(text) = e {
                    Some(Layer::new(text, tileset, width, height))
                } else {
                    None
                }
            })
            .collect();

        let spawns = Map::get_spawn_points(&layers, tileset.get_spawn_tiles());

        Map {
            layers,
            width,
            height,
            spawns,
        }
    }

    fn get_spawn_points(
        layers: &[Layer],
        spawn_tiles: Vec<(String, usize)>,
    ) -> Vec<(String, Point2<f32>)> {
        let mut spawn_points = Vec::new();

        for layer in layers.iter() {
            for tile in layer.tiles.iter() {
                for spawn_tile in spawn_tiles.iter() {
                    if spawn_tile.1 == tile.id {
                        spawn_points.push((spawn_tile.0.clone(), tile.destination));
                    }
                }
            }
        }

        spawn_points
    }

    pub fn draw(&self, spritebatch: &mut SpriteBatch) {
        for layer in self.layers.iter() {
            layer.draw(spritebatch);
        }
    }

    pub fn update(&mut self) {
        for layer in self.layers.iter_mut() {
            layer.update();
        }
    }

    pub fn get_spawns(&self) -> Vec<(String, Point2<f32>)> {
        self.spawns.clone()
    }

    pub fn get_dimensions(&self) -> (f32, f32) {
        (
            (constants::TILE_WIDTH * constants::TILE_SCALE) * self.width as f32,
            (constants::TILE_HEIGHT * constants::TILE_SCALE) * self.height as f32,
        )
    }
}