aboutsummaryrefslogtreecommitdiff
path: root/level_map.wren
blob: 2bfb9411cc15c8ed23bb7581b04855dfb8b638b2 (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
import "json" for Json
import "graphics" for ImageData
import "math" for Math
import "./layer_type" for LayerType

class LevelMap {
    construct new(mapName) {
        _mapData = Json.load("assets/%(mapName).json")
        var tileSheetData =  _mapData["tilesets"][0] // Assuming there is only a single tilesheet/level
        _tileSheet = ImageData.loadFromFile("assets/%(tileSheetData["image"])")
        _tileSheetH = tileSheetData["imageheight"]
        _tileSheetW = tileSheetData["imagewidth"]
        _tileH = tileSheetData["tileheight"]
        _tileW = tileSheetData["tilewidth"]
        _mapHeight = _mapData["height"]
        _mapWidth = _mapData["width"]
        _layers = _mapData["layers"]
        _rows = Math.floor(_tileSheetW/_tileW)
        _cols = Math.floor(_tileSheetH/_tileH)
    }

    draw(x, y) {
        var startX = x
        var startY = y
        for(layer in _layers) {
            var index = 0        
            for(mapYV in 0...(_mapHeight)) {
                for(mapXV in 0...(_mapWidth)) {
                    if((layer["type"] == LayerType.Tile) && (layer["visible"] == true)) {
                        var tileIndex = layer["data"][index]
                        if (tileIndex > 0) {
                            drawTile(tileIndex-1, x, y)
                        }
                    }
                    index = index + 1
                    x = x + 16
                }
                y = y + 16
                x = startX
            }
            x = startX
            y = startY
        }
    }

    drawTile(tileIndex, mapX, mapY) {
        var spriteX = (tileIndex % _rows)
        var spriteY = Math.floor ((tileIndex - spriteX) % _cols)
        _tileSheet.transform({
            "srcX": spriteX * 16,
            "srcY": spriteY * 16,
            "srcW": _tileW,
            "srcH": _tileH,
            "scaleX": 1,
            "scaleY": 1
        }).draw(mapX,mapY)
    }
}