xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / internal / world / path.go 75 lines1.6 kB Raw
1package world
2
3import (
4	"container/heap"
5
6	"tinyadventure/internal/model"
7)
8
9type node struct {
10	at   [2]int
11	cost int
12}
13
14type frontier []node
15
16func (f frontier) Len() int           { return len(f) }
17func (f frontier) Less(i, j int) bool { return f[i].cost < f[j].cost }
18func (f frontier) Swap(i, j int)      { f[i], f[j] = f[j], f[i] }
19func (f *frontier) Push(x any)        { *f = append(*f, x.(node)) }
20func (f *frontier) Pop() any {
21	old := *f
22	n := old[len(old)-1]
23	*f = old[:len(old)-1]
24	return n
25}
26
27func Path(m *model.Map, from, to [2]int, blocked func(x, y int) bool) [][2]int {
28	if !m.Walkable(to[0], to[1]) {
29		return nil
30	}
31	prev := map[[2]int][2]int{from: from}
32	best := map[[2]int]int{from: 0}
33	open := &frontier{{from, 0}}
34	for open.Len() > 0 {
35		c := heap.Pop(open).(node)
36		if c.at == to {
37			var out [][2]int
38			for at := to; at != from; at = prev[at] {
39				out = append([][2]int{at}, out...)
40			}
41			return out
42		}
43		if c.cost > best[c.at] {
44			continue
45		}
46		for _, n := range Neighbours(c.at[0], c.at[1]) {
47			if !m.Walkable(n[0], n[1]) || (n != to && blocked != nil && blocked(n[0], n[1])) {
48				continue
49			}
50			cost := c.cost + m.Cost(n[0], n[1])
51			if old, seen := best[n]; seen && old <= cost {
52				continue
53			}
54			best[n], prev[n] = cost, c.at
55			heap.Push(open, node{n, cost})
56		}
57	}
58	return nil
59}
60
61func Reach(m *model.Map, from [2]int) map[[2]int]bool {
62	seen := map[[2]int]bool{from: true}
63	queue := [][2]int{from}
64	for len(queue) > 0 {
65		c := queue[0]
66		queue = queue[1:]
67		for _, n := range Neighbours(c[0], c[1]) {
68			if !seen[n] && m.Walkable(n[0], n[1]) {
69				seen[n] = true
70				queue = append(queue, n)
71			}
72		}
73	}
74	return seen
75}