1
0
mirror of https://github.com/maaslalani/gambit.git synced 2025-01-18 02:58:41 +02:00
gambit/position/position.go

50 lines
1.3 KiB
Go
Raw Normal View History

2021-12-21 23:24:53 -05:00
package position
import (
"fmt"
"strconv"
)
2021-12-21 23:53:35 -05:00
// Position represents a position on the board
2021-12-21 23:24:53 -05:00
type Position struct {
2021-12-21 23:53:35 -05:00
// Row represents the row number of the cell in the board,
// this can easily be converted to a human readable rank
2021-12-21 23:24:53 -05:00
Row int // rank
2021-12-21 23:53:35 -05:00
// Col represents the column number of the cell in the board,
// this can easily be converted to a human readable file
2021-12-21 23:24:53 -05:00
Col int // file
}
2021-12-21 23:53:35 -05:00
// String takes the current position and returns a human readable file and
// rank in chess notation
2021-12-21 23:24:53 -05:00
func (p Position) String() string {
2021-12-21 23:53:35 -05:00
return ColumnToFile(p.Col) + RowToRank(p.Row)
2021-12-21 23:24:53 -05:00
}
2021-12-21 23:53:35 -05:00
// ToPosition reads a rank and file number and returns the corresponding
// position on the board's grid
2021-12-21 23:24:53 -05:00
func ToPosition(s string) Position {
return Position{RankToRow(s[1]), FileToColumn(s[0])}
}
2021-12-21 23:53:35 -05:00
// RowToRank converts a row number to a human readable rank
func RowToRank(row int) string {
return fmt.Sprintf("%d", row+1)
2021-12-21 23:24:53 -05:00
}
2021-12-21 23:53:35 -05:00
// RankToRow converts a human readable rank number to a board row number
2021-12-21 23:24:53 -05:00
func RankToRow(rank byte) int {
parsed, _ := strconv.Atoi(string(rank))
return parsed - 1
}
2021-12-21 23:53:35 -05:00
// ColumnToFile converts a column number to a human readable file
2021-12-21 23:24:53 -05:00
func ColumnToFile(column int) string {
return fmt.Sprintf("%c", column+'A')
}
2021-12-21 23:53:35 -05:00
// FileToColumn converts a human readable file to a board column number
2021-12-21 23:24:53 -05:00
func FileToColumn(file byte) int {
return int(file - 'A')
}