// Package minesweeper handles minesweeper game.
package minesweeper
import (
"fmt"
)
// Count counts mines related to each field.
func (b Board) Count() error {
for j := range b {
if len(b[j]) != len(b[0]) {
return fmt.Errorf("non-square minefield")
}
if b[j][0] != '+' && b[j][0] != '|' {
return fmt.Errorf("invalid minefield fence")
}
for i := range b[j] {
if b[j][i] == 'X' {
return fmt.Errorf("invalid field value")
}
if b[j][i] == ' ' {
b[j][i] = b.countMines(j, i)
}
}
}
return nil
}
func (b Board) countMines(row, col int) byte {
var sum byte
for j := -1; j < 2; j++ {
for i := -1; i < 2; i++ {
// skip first and last row and column as those are just marking the minefield
if row+j < 1 || row+j > len(b)-2 {
continue
}
if col+i < 1 || col+i > len(b[0])-2 {
continue
}
if b[row+j][col+i] == '*' {
sum++
}
}
}
if sum == 0 {
return ' '
}
return sum + 48 // convert to character
}