~technomancy/tremendous-quest-iv

tremendous-quest-iv/pathfinding.fnl -rw-r--r-- 1.9 KiB
a3c24536Phil Hagelberg Bump to Fennel 0.9.1; fix some bugs. 5 months ago
                                                                                
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
(local Grid (require :lib.jumper.grid))
(local Pathfinder (require :lib.jumper.pathfinder))
(local util (require :util))

(fn zeroed-rows [width height]
  (let [ret []]
    (var y 1)
    (while (<= y height)
      (let [row []]
        (var x 1)
        (while (<= x width)
          (tset row x 0)
          (set x (+ x 1)))
        (tset ret y row)
        (set y (+ y 1))))
    ret))

(fn generate-grid-from-tiled-map [tiled-map]
  (let [grid (zeroed-rows tiled-map.width tiled-map.height)]
    (each [_ layer (ipairs tiled-map.layers)]
      (when (and layer.properties.collidable layer.data)
        (each [relative-y row (pairs layer.data)]
          (each [relative-x tile (pairs row)]
            (let [y (+ relative-y layer.y) x (+ relative-x layer.x)]
              (tset (. grid y) x 1))))))
    (Grid grid)))

(fn finder-from-tiled-map [tiled-map]
  (-> tiled-map
      generate-grid-from-tiled-map
      (Pathfinder :JPS 0)))

(fn path->points [path]
  (let [ret []]
    (var i 1)
    (each [node count (path:nodes)]
      (tset ret i (node:getX))
      (tset ret (+ i 1) (node:getY))
      (set i (+ i 2)))
    ret))

;; turns path points, which are coordinates to tiles, to absolute
;; points in the game world. centers the points within the respective
;; tiles
(fn path-points->absolute-points [...]
  (->> ...
       (util.transform-points -1 -1)
       (util.scale-points 16)))

;; takes an object with the same shape as state.viewport
(fn path-points->view-points [{: x : y : scale} ...]
  (->> ...
       path-points->absolute-points
       (util.scale-points scale)
       (util.transform-points x y)))

(fn absolute-points->path-points [...]
  (->> ...
       (util.scale-points (/ 1 16))
       (util.floor-points)))

{: generate-grid-from-tiled-map
 : finder-from-tiled-map
 : path->points
 : path-points->absolute-points
 : path-points->view-points
 : absolute-points->path-points}