freego/board.go

90 lines
1.8 KiB
Go
Raw Normal View History

2022-02-21 19:07:28 -05:00
package freego
2022-02-18 18:36:18 -05:00
import "errors"
//Board represents main game board
type Board struct {
board [][]*Tile
size int
}
//NewBoard creates a new board instance
func NewBoard(size int) *Board {
2022-02-20 16:07:20 -05:00
if size < 4 || size%2 != 0 {
return nil
}
2022-02-18 18:36:18 -05:00
b := make([][]*Tile, size)
var colour Colour
for i := 0; i < size; i++ {
b[i] = make([]*Tile, size)
if i < size/2 {
2022-02-20 16:07:20 -05:00
colour = Blue
2022-02-20 17:06:39 -05:00
} else {
colour = Red
2022-02-18 18:36:18 -05:00
}
for j := 0; j < size; j++ {
b[i][j] = &Tile{i, j, true, nil, colour}
}
}
return &Board{
board: b,
size: size,
}
}
func (b *Board) validatePoint(x, y int) bool {
if x < 0 || x >= len(b.board) {
return false
}
if y < 0 || y >= len(b.board) {
return false
}
return true
}
//GetPiece returns the piece at a given location
func (b *Board) GetPiece(x, y int) (*Piece, error) {
if !b.validatePoint(x, y) {
return nil, errors.New("GetPiece invalid location")
}
2022-02-20 18:34:38 -05:00
return b.board[y][x].Piece(), nil
2022-02-18 18:36:18 -05:00
}
//Place a piece on the board; returns false if a piece is already there
func (b *Board) Place(x, y int, p *Piece) (bool, error) {
if !b.validatePoint(x, y) {
return false, errors.New("Place invalid location")
}
2022-02-20 18:34:38 -05:00
if b.board[y][x].Piece() != nil {
2022-02-18 18:36:18 -05:00
return false, nil
}
2022-02-20 18:34:38 -05:00
err := b.board[y][x].Place(p)
2022-02-18 18:36:18 -05:00
if err != nil {
return false, err
}
return true, nil
}
//Remove a piece from a tile
func (b *Board) Remove(x, y int) error {
if !b.validatePoint(x, y) {
return errors.New("Remove invalid location")
}
2022-02-20 18:34:38 -05:00
b.board[y][x].Remove()
2022-02-18 18:36:18 -05:00
return nil
}
//GetColor returns color of tile
func (b *Board) GetColor(x, y int) Colour {
2022-02-20 18:34:38 -05:00
return b.board[y][x].Colour()
2022-02-18 18:36:18 -05:00
}
2022-02-20 16:07:20 -05:00
//AddTerrain puts a river tile at specified location
func (b *Board) AddTerrain(x, y, t int) (bool, error) {
2022-02-18 18:36:18 -05:00
if !b.validatePoint(x, y) {
return false, errors.New("River invalid location")
}
2022-02-20 18:34:38 -05:00
b.board[y][x].AddTerrain(t)
2022-02-18 18:36:18 -05:00
return true, nil
}