-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
366 lines (327 loc) · 8.03 KB
/
main.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2020 Andrew Ekstedt
// This program is licensed under the GNU Affero General
// Public License v3.0. See LICENSE for details.
package main
import (
"container/heap"
"flag"
"fmt"
"io/ioutil"
"log"
"math/bits"
"os"
"runtime"
"time"
)
func main() {
mapflag := flag.String("map", "", "levelset to load walls from [required]")
outflag := flag.String("o", "", "file to save generated level to [optional]")
progressflag := flag.Bool("progress", false, "show progress")
flag.Parse()
var progress <-chan time.Time
if *progressflag {
progress = time.Tick(1 * time.Second)
}
var g Generator
g.progress = progress
if *mapflag == "" {
fmt.Fprintln(os.Stderr, "error: -map flag is required")
os.Exit(1)
} else {
data, err := ioutil.ReadFile(*mapflag)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
level, err := DecodeLevel(data)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
g.walls = Bitmap{}
foundPlayer := false
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
p := Point{X: int8(x), Y: int8(y)}
switch level.Tiles[y][x] {
case Wall:
g.walls.Set(int8(x), int8(y), true)
case Teleport:
g.sink = p
case Player:
g.startPos = p
foundPlayer = true
}
}
}
if !foundPlayer {
loop:
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if level.Tiles[y][x] == Floor {
g.startPos.X = int8(x)
g.startPos.Y = int8(y)
break loop
}
}
}
}
}
for i := range g.walls {
g.walls[i] |= 0xFFFF >> width << width
}
//fmt.Println(g.walls.String())
node := g.Search()
fmt.Println(node.len)
fmt.Println(node.state.pos)
for n := node; n != nil; n = n.parent {
fmt.Print(formatLevel(&g, n))
fmt.Println("-")
}
//pretty.Println(node.state)
if node.len < len(g.count) {
fmt.Println("found", g.count[node.len], "solutions of length", node.len)
}
if *outflag != "" {
var level Level
level.Title = "Computer"
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if g.walls.At(int8(x), int8(y)) {
level.Tiles[y][x] = Wall
} else if node.state.blocks.At(int8(x), int8(y)) {
level.Tiles[y][x] = Block
}
}
}
level.Tiles[node.state.pos.Y][node.state.pos.X] = Player
level.Tiles[g.sink.Y][g.sink.X] = Teleport
err := SaveLevel(*outflag, &level)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
}
type Generator struct {
// TODO: add a separate field for unenterable tiles
// and let walls just be walls
walls Bitmap
sink Point // where the block have to go (come from)
startPos Point
count [256]int
progress <-chan time.Time
}
// Normal sokoban:
// a block can be pushed if square 2 is reachable and square 0 is not blocked
//
// _ [] P -> [] P _
// 0 1 2 0 1 2
//
// backwards sokoban:
// a block can be pulled if square 1 is reachable and square 2 is not blocked
//
// [] P _ -> _ [] P
// 0 1 2 0 1 2
type Point struct{ Y, X int8 }
var dirs = [4]Point{
{-1, 0}, {+1, 0}, {0, -1}, {0, +1},
}
// number of squares to consider during a block line
// if set to 1 this becomes the normal push metric
const maxPush = 1
func (g *Generator) Search() *node {
var visited = make(map[state]struct{})
var queue nodeQueue // []*node
var start = new(node)
var max = start
var blocks []Point
start.state.blocks.Set(g.sink.X, g.sink.Y, true)
start.state.pos = g.startPos
start.state.normalize(&g.walls)
log.Print("\n", formatLevel(g, start))
queue = append(queue, start)
for len(queue) > 0 {
no := heap.Pop(&queue).(*node)
if _, ok := visited[no.state]; ok {
continue
}
visited[no.state] = struct{}{}
if no.len < len(g.count) {
g.count[no.len]++
}
if no.len > max.len {
max = no
}
select {
case <-g.progress:
var m runtime.MemStats
runtime.ReadMemStats(&m)
log.Printf("alloc: current %d MB, max %d MB, sys %d MB", m.Alloc/1e6, m.TotalAlloc/1e6, m.Sys/1e6)
log.Printf("search: current %d, max %d, visited: %d, queue %d\n%s", no.len, max.len, len(visited), len(queue),
no.state.blocks.String())
default:
}
// find reachable squares
r := reachable(no.state.pos.X, no.state.pos.Y, &g.walls, &no.state.blocks)
// find blocks
blocks = blocks[:0]
for i, bl := range no.state.blocks {
/// TODO: maybe mask bl with r?
for bl != 0 {
y := i
x := bits.Len16(bl) - 1
bl = bl & ((1 << x) - 1) // clear current block
if !no.state.blocks.At(int8(x), int8(y)) {
panic("block does not exist")
}
blocks = append(blocks, Point{X: int8(x), Y: int8(y)})
}
}
// iterate over each block
// and find valid moves
for _, p := range blocks {
x, y := int(p.X), int(p.Y)
for _, d := range dirs {
dx, dy := int(d.X), int(d.Y)
// square beside the block must be
// reachable and not blocked
if x+dx < 0 || x+dx >= width {
continue
}
if y+dy < 0 || y+dy >= height {
continue
}
if !r.At(int8(x+dx), int8(y+dy)) {
continue
}
// block lines metric:
// pulling a block multiple squares in one direction
// counts as a single move
for j := 1; j < maxPush+1; j++ {
// in order to pull,
// (j+1) squares in the pull direction
// must be reachable & clear
if x+dx*(j+1) < 0 || x+dx*(j+1) >= width {
break
}
if y+dy*(j+1) < 0 || y+dy*(j+1) >= height {
break
}
if !r.At(int8(x+dx*(j+1)), int8(y+dy*(j+1))) {
break
}
new := newnode()
*new = node{
state: no.state,
parent: no,
len: no.len + 1,
}
// set the new block position
new.state.blocks.Set(int8(x), int8(y), false)
new.state.blocks.Set(int8(x+dx*j), int8(y+dy*j), true)
// there is always a block at the sink
new.state.blocks.Set(g.sink.X, g.sink.Y, true)
// update pos
new.state.pos.X = int8(x + dx*(j+1))
new.state.pos.Y = int8(y + dy*(j+1))
new.state.normalize(&g.walls)
// add to the heap
if _, ok := visited[new.state]; ok {
continue
}
heap.Push(&queue, new)
}
}
}
}
log.Println("visited ", len(visited), "states")
return max
}
func (s *state) normalize(walls *Bitmap) {
r := reachable(s.pos.X, s.pos.Y, &s.blocks, walls)
for i := range r {
if r[i] != 0 {
s.pos.Y = int8(i)
s.pos.X = int8(bits.Len16(r[i]) - 1)
return
}
}
}
// Return a bitmap of all squares reachable from x,y
// without visiting mask1 or mask2
func reachable(x, y int8, mask1, mask2 *Bitmap) Bitmap {
var a Bitmap
a.Set(x, y, true)
for {
prev := uint16(0)
changed := uint16(0)
for i := 0; i < len(a); i++ {
tmp := a[i]
tmp2 := tmp | tmp<<1 | tmp>>1 | prev
if i+1 < len(a) {
tmp2 |= a[i+1]
}
tmp2 &^= mask1[i]
tmp2 &^= mask2[i]
changed |= tmp2 &^ tmp
a[i] |= tmp2
prev = tmp
}
if changed == 0 {
break
}
}
return a
}
type node struct {
state state
parent *node
len int
}
type state struct {
blocks Bitmap
pos Point // position of player after last pull
}
type nodeQueue []*node
func (h nodeQueue) Len() int { return len(h) }
func (h nodeQueue) Less(i, j int) bool { return h[i].len < h[j].len }
func (h nodeQueue) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *nodeQueue) Push(x interface{}) { *h = append(*h, x.(*node)) }
func (h *nodeQueue) Pop() interface{} {
x := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return x
}
var nodepool []node
// bump allocator for nodes
func newnode() *node {
if len(nodepool) == 0 {
nodepool = make([]node, 100000)
}
node := &nodepool[0]
nodepool = nodepool[1:]
return node
}
func formatLevel(g *Generator, n *node) string {
var s []byte
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if g.walls.At(int8(x), int8(y)) {
s = append(s, "##"...)
} else if n.state.blocks.At(int8(x), int8(y)) {
s = append(s, "[]"...)
} else if x == int(n.state.pos.X) && y == int(n.state.pos.Y) {
s = append(s, "$ "...)
} else {
if y%2 == 0 {
s = append(s, ". "...)
} else {
s = append(s, " ,"...)
}
}
}
s = append(s, '\n')
}
return string(s)
}