mchess-server/types/coordinate.go

128 lines
2.6 KiB
Go
Raw Normal View History

package types
// coordinates starting at 1:1 and end at 8:8
type Coordinate struct {
Col int `json:"col"`
Row int `json:"row"`
}
const (
RangeLastValid = 8
RangeFirstValid = 1
RangeUpperInvalid = 9
RangeLowerInvalid = 0
)
func (c Coordinate) Up(number int) *Coordinate {
check := c.Row + number
if check <= RangeLastValid {
return &Coordinate{Row: check, Col: c.Col}
}
return nil
}
func (c Coordinate) Down(number int) *Coordinate {
check := c.Row - number
if check >= RangeFirstValid {
return &Coordinate{Row: check, Col: c.Col}
}
return nil
}
// Right and left is seen from a board where row 1 is on the bottom
func (c Coordinate) Right(number int) *Coordinate {
check := c.Col + number
if check <= RangeLastValid {
return &Coordinate{Row: c.Row, Col: check}
}
return nil
}
func (c Coordinate) Left(number int) *Coordinate {
check := c.Col - number
if check >= RangeFirstValid {
return &Coordinate{Row: c.Row, Col: check}
}
return nil
}
func (c Coordinate) GetAllSquaresLeft() []Coordinate {
squares := []Coordinate{}
i := 1
for {
if square := c.Left(i); square != nil {
squares = append(squares, *square)
i += 1
} else {
return squares
}
}
}
func (c Coordinate) GetAllSquaresRight() []Coordinate {
squares := []Coordinate{}
i := 1
for {
if square := c.Right(i); square != nil {
squares = append(squares, *square)
i += 1
} else {
return squares
}
}
}
func (c Coordinate) GetAllSquaresAbove() []Coordinate {
squares := []Coordinate{}
i := 1
for {
if square := c.Up(i); square != nil {
squares = append(squares, *square)
i += 1
} else {
return squares
}
}
}
func (c Coordinate) GetAllSquaresBelow() []Coordinate {
squares := []Coordinate{}
i := 1
for {
if square := c.Down(i); square != nil {
squares = append(squares, *square)
i += 1
} else {
return squares
}
}
}
func (c Coordinate) GetSquaresOnRow() []Coordinate {
rowToReturn := []Coordinate{}
leftMostSquareOnRow := Coordinate{Col: RangeFirstValid, Row: c.Row}
index := 0
for {
squareToAppend := leftMostSquareOnRow.Right(index)
if squareToAppend == nil {
break
}
rowToReturn = append(rowToReturn, *squareToAppend)
index = index + 1
}
return rowToReturn
}
func (c Coordinate) GetSquaresOnColumn() []Coordinate {
columnToReturn := []Coordinate{}
bottomSquareOnColumn := Coordinate{Col: c.Col, Row: RangeFirstValid}
index := 0
for {
squareToAppend := bottomSquareOnColumn.Up(index)
if squareToAppend == nil {
break
}
columnToReturn = append(columnToReturn, *squareToAppend)
index = index + 1
}
return columnToReturn
}