~bigbes/game-prototype-ftl

ref: 1b674aa54513febeb3d317027977e0fd80c992ff game-prototype-ftl/tiles.go -rw-r--r-- 1.4 KiB
1b674aa5 — Eugene Blikh feat(crew): restrict movement to room cell slots 6 days 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
68
69
package main

func walkableTiles(s Ship) map[[2]int]bool {
	walk := make(map[[2]int]bool)
	for _, r := range s.Rooms {
		for y := r.GridY; y < r.GridY+r.GridH; y++ {
			for x := r.GridX; x < r.GridX+r.GridW; x++ {
				walk[[2]int{x, y}] = true
			}
		}
	}
	return walk
}

func cellSet(s Ship) map[[2]int]bool {
	cells := make(map[[2]int]bool)
	for _, r := range s.Rooms {
		for _, c := range r.Cells {
			cells[c] = true
		}
	}
	return cells
}

func bfsPath(walk map[[2]int]bool, from, to [2]int) [][2]int {
	if from == to {
		return nil
	}
	if !walk[to] {
		return nil
	}

	neighbours := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
	visited := map[[2]int]bool{from: true}
	parent := map[[2]int][2]int{}
	queue := [][2]int{from}

	for len(queue) > 0 {
		cur := queue[0]
		queue = queue[1:]
		for _, d := range neighbours {
			next := [2]int{cur[0] + d[0], cur[1] + d[1]}
			if !walk[next] || visited[next] {
				continue
			}
			visited[next] = true
			parent[next] = cur
			if next == to {
				return reconstructPath(parent, from, to)
			}
			queue = append(queue, next)
		}
	}
	return nil
}

func reconstructPath(parent map[[2]int][2]int, from, to [2]int) [][2]int {
	var path [][2]int
	cur := to
	for cur != from {
		path = append(path, cur)
		cur = parent[cur]
	}
	// reverse
	for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
		path[i], path[j] = path[j], path[i]
	}
	return path
}