-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine.go
412 lines (344 loc) · 8.6 KB
/
engine.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package minesweeper
import (
"container/list"
"crypto/rand"
"encoding/binary"
"fmt"
"sync"
"github.com/rrborja/minesweeper/visited"
)
type eventType uint8
type blocks [][]Block
const consecutiveRandomLimit = 3
const easyMultiplier = 0.1
const mediumMultiplier = 0.2
const hardMultiplier = 0.5
type board struct {
*Grid
blocks
difficultyMultiplier float32
}
type game struct {
Event
board
Difficulty
recordedActions
*sync.Mutex
}
var singleton Minesweeper
func (game *game) SetGrid(width, height int) error {
if game.Grid != nil {
return new(GameAlreadyStartedError)
}
game.Grid = &Grid{width, height}
createBoard(game)
return nil
}
func (game *game) Flag(x, y int) {
blockPtr := &game.blocks[x][y]
if !blockPtr.visited {
blockPtr.flagged = !blockPtr.flagged
}
}
func (game *game) Visit(x, y int) ([]Block, error) {
game.validateGameEnvironment()
game.Lock()
defer game.Unlock()
block := &game.blocks[x][y]
if block.Node == Number && block.visited {
countedFlaggedBlock := 0
resultedBlocks := make([]Block, 0)
blocksToBeVisited := make([]*Block, 0)
game.traverseAdjacentCells(x, y, func(cell *Block) {
if cell.flagged {
countedFlaggedBlock++
} else {
blocksToBeVisited = append(blocksToBeVisited, cell)
}
})
if countedFlaggedBlock == block.Value {
for _, block := range blocksToBeVisited {
blocks, err := game.visit(block.X(), block.Y())
if err != nil {
return blocks, err
}
resultedBlocks = append(resultedBlocks, blocks...)
}
}
return resultedBlocks, nil
}
return game.visit(x, y)
}
func (game *game) visit(x, y int) ([]Block, error) {
block := &game.blocks[x][y]
if !block.flagged && !block.visited {
block.visited = true
defer func() {
go game.validateSolution()
}()
switch block.Node {
case Number:
defer game.add(visited.Record{
Position: *block, Action: visited.Number})
return []Block{*block}, nil
case Bomb:
defer game.add(visited.Record{
Position: *block, Action: visited.Bomb})
bombLocations := make([]Block, 0, game.totalBombs()-1)
for _, bombLocation := range game.BombLocations() {
if bombLocation != *block {
bombLocations = append(bombLocations, bombLocation.(Block))
}
}
bombLocations = append([]Block{*block}, bombLocations...)
return bombLocations, &ExplodedError{x: x, y: y}
case Unknown:
defer game.add(visited.Record{
Position: *block, Action: visited.Unknown})
block.visited = false //to avoid infinite recursion, first is to set the base case
visitedList := list.New()
autoRevealUnmarkedBlock(game, visitedList, x, y)
visitedBlocks := make([]Block, visitedList.Len())
var counter int
for e := visitedList.Front(); e != nil; e = e.Next() {
visitedBlocks[counter] = e.Value.(Block)
counter++
}
return visitedBlocks, nil
}
}
return nil, nil
}
func (game *game) SetDifficulty(difficulty Difficulty) error {
if game.Mutex != nil {
return new(GameAlreadyStartedError)
}
game.Difficulty = difficulty
switch difficulty {
case Easy:
game.difficultyMultiplier = easyMultiplier
case Medium:
game.difficultyMultiplier = mediumMultiplier
case Hard:
game.difficultyMultiplier = hardMultiplier
}
return nil
}
func (game *game) Play() error {
if game.Difficulty == notSet {
return new(UnspecifiedDifficultyError)
}
if game.Grid == nil {
return new(UnspecifiedGridError)
}
if game.Mutex != nil {
return new(GameAlreadyStartedError)
}
game.Mutex = new(sync.Mutex)
createBombs(game)
tallyHints(game)
return nil
}
// X returns the X coordinate of the block in the minesweeper grid
func (block Block) X() int {
return block.location.x
}
// Y returns the Y coordinate of the block in the minesweeper grid
func (block Block) Y() int {
return block.location.y
}
// Shifts to the right
func shiftPosition(grid *Grid, x, y int) (_x, _y int) {
width := grid.Width
height := grid.Height
if x+1 >= width {
if y+1 >= height {
_x, _y = 0, 0
} else {
_x, _y = 0, y+1
}
} else {
_x, _y = x+1, y
}
return
}
func createBombs(game *game) {
area := int(game.Width * game.Height)
for i := 0; i < int(float32(area)*game.difficultyMultiplier); i++ {
for {
randomPos := randomNumber(area)
x, y := randomPos%game.Width, randomPos/game.Width
countLimit := 0
for game.board.blocks[x][y].Node != Unknown {
x, y = shiftPosition(game.Grid, x, y)
countLimit++
}
if countLimit <= consecutiveRandomLimit {
game.blocks[x][y].Node = Bomb
break
}
}
}
}
func tallyHints(game *game) {
game.iterateBlocksWhen(Bomb, func(block *Block) {
game.traverseAdjacentCells(block.X(), block.Y(), func(cell *Block) {
if cell.Node != Bomb {
cell.Node = Number
cell.Value++
}
})
})
}
func createBoard(game *game) {
game.blocks = make([][]Block, game.Width)
for x := range game.blocks {
game.blocks[x] = make([]Block, game.Height)
}
for x, row := range game.blocks {
for y := range row {
block := &game.blocks[x][y]
block.Value = 0
block.Node = Unknown
block.location = struct{ x, y int }{x: x, y: y}
}
}
}
func autoRevealUnmarkedBlock(game *game, visitedBlocks *list.List, x, y int) {
blocks := game.blocks
game.withinBounds(x, y, func() {
if blocks[x][y].visited {
return
}
switch blocks[x][y].Node {
case Unknown:
blocks[x][y].visited = true
visitedBlocks.PushBack(blocks[x][y])
game.traverseAdjacentCells(x, y, func(cell *Block) {
autoRevealUnmarkedBlock(game, visitedBlocks, cell.X(), cell.Y())
})
case Number:
blocks[x][y].visited = true
visitedBlocks.PushBack(blocks[x][y])
}
})
}
func (game *game) validateSolution() {
defer skipIterate()
var visitTally int
game.iterateVisitedBlocks(func(block *Block) {
switch block.Node {
case Bomb:
game.Event <- Lose
panic("")
default:
visitTally++
}
})
if visitTally == game.totalNonBombs() {
game.Event <- Win
}
}
func (game *game) validateGameEnvironment() {
if game.Grid == nil {
panic(UnspecifiedGridError{})
}
if game.Difficulty == notSet {
panic(UnspecifiedDifficultyError{})
}
}
func (game *game) traverseAdjacentCells(x, y int, do func(*Block)) {
game.recursivelyTraverseAdjacentCells(x-1, y-1, do)
game.recursivelyTraverseAdjacentCells(x, y-1, do)
game.recursivelyTraverseAdjacentCells(x+1, y-1, do)
game.recursivelyTraverseAdjacentCells(x-1, y, do)
game.recursivelyTraverseAdjacentCells(x+1, y, do)
game.recursivelyTraverseAdjacentCells(x-1, y+1, do)
game.recursivelyTraverseAdjacentCells(x, y+1, do)
game.recursivelyTraverseAdjacentCells(x+1, y+1, do)
}
func (game *game) recursivelyTraverseAdjacentCells(x, y int, do func(*Block)) {
game.withinBounds(x, y, func() {
do(&game.blocks[x][y])
})
}
func (game *game) withinBounds(x, y int, do func()) {
width := game.Width
height := game.Height
if x >= 0 && y >= 0 && x < width && y < height {
do()
}
}
func (game *game) iterateBlocks(do func(*Block) bool) bool {
defer skipIterate()
for x := 0; x < game.Width; x++ {
for y := 0; y < game.Height; y++ {
do(&game.blocks[x][y])
}
}
return true
}
func (game *game) iterateBlocksWhen(condition Node, do func(*Block)) bool {
return game.iterateBlocks(func(block *Block) bool {
defer skipIterate()
if block.Node&condition == condition {
do(block)
}
return true
})
}
func (game *game) iterateVisitedBlocks(do func(*Block)) bool {
return game.iterateBlocks(func(block *Block) bool {
defer skipIterate()
if block.visited {
do(block)
}
return true
})
}
func skipIterate() bool {
recover()
return false
}
func (game *game) area() int {
return len(game.blocks) * len(game.blocks[0])
}
func (game *game) areaInFloat() float32 {
return float32(game.area())
}
func (game *game) totalBombs() int {
return int(game.areaInFloat() * game.difficultyMultiplier)
}
func (game *game) totalNonBombs() int {
return game.area() - game.totalBombs()
}
// Visited responds if a cell is visited or not
func (block *Block) Visited() bool {
return block.visited
}
// Flagged responds if a cell is visited or not
func (block *Block) Flagged() bool {
return block.flagged
}
func (block Block) String() string {
var nodeType string
switch block.Node {
case Unknown:
nodeType = "blank"
case Number:
nodeType = "number"
case Bomb:
nodeType = "bomb"
}
var value string
if block.Value > 0 {
value = string(block.Value)
}
return fmt.Sprintf("\n\nBlock: \n\tValue\t :\t%v\n\tLocation :\tx:%v y:%v\n\tType\t :\t%v\n\tVisited? :\t%v\n\tFlagged? :\t%v\n\n",
value, block.location.x, block.location.y, nodeType, block.visited, block.flagged)
}
func randomNumber(max int) int {
var number uint16
binary.Read(rand.Reader, binary.LittleEndian, &number)
return int(number) % max
}