-
Notifications
You must be signed in to change notification settings - Fork 0
/
cell.go
75 lines (63 loc) · 1.06 KB
/
cell.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
package minesweeper
import (
"errors"
"strconv"
)
type CellType int
const (
CellTypeMine CellType = iota
CellTypeAdjacent
)
type Cell struct {
X int
Y int
Revealed bool
Flagged bool
AdjMines int
Type CellType
}
func NewCell(cellType CellType, x, y int) (*Cell, error) {
return &Cell{
X: x,
Y: y,
Type: cellType,
}, nil
}
func (c *Cell) Reveal() {
c.Flagged = false
c.Revealed = true
}
func (c *Cell) ToggleFlag() error {
if c.Revealed {
return errors.New("cannot flag a revealed cell")
}
c.Flagged = !c.Flagged
return nil
}
func (c *Cell) AdjacentCells(grid [][]*Cell) []*Cell {
adj := []*Cell{}
deltas := [][2]int{
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1},
}
for _, delta := range deltas {
dx, dy := delta[0], delta[1]
x, y := c.X+dx, c.Y+dy
if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {
adj = append(adj, grid[x][y])
}
}
return adj
}
func (c Cell) String() string {
if c.Type == CellTypeMine {
return "💣"
}
return strconv.Itoa(c.AdjMines)
}