Recently I have started building a chess game in GoLang and one issue I'm facing is storing different characters (i.e. Pawn, Knight, King) in a single array.
package main
import "fmt"
type character struct {
currPosition [2]int
}
type Knight struct {
c character
}
func (K Knight) Move() {
fmt.Println("Moving Kinght...")
}
type King struct {
c character
}
func (K King) Move() {
fmt.Println("Moving King...")
}
In the above case, can we have Knight and King in the same array since they are inherited from the same base class?
Like
characters := []character{Knight{}, King{}}
CodePudding user response:
Go doesn't have classes and inheritance. Compile-time polymorphism is not possible in Go (since method overloading is not supported). It only has Runtime Polymorphism. But it has a concept called composition. Where the struct is used to form other objects.
You can read here why Golang doesn't have inheritance like OOP concepts in other programming languages. https://www.geeksforgeeks.org/inheritance-in-golang/
OR
Instead of implementing chess pieces separately, you can have single struct for all of them with different values of respective attributes.
// Piece represents a chess piece
type Piece struct {
Name string
Color string
PosX int
PosY int
Moves int
Points int
}
type Board struct {
Squares [8][8]*Piece
}
func (b *Board) MovePiece(p *Piece, x, y int){
// Your logic to move a chess piece.
}
...
// and make objects for Piece struct as you build the board.
king := &Piece{Name: "King", Color: "White", Points: 10}
OR
You must use interface if you want to implement chess pieces separately.
CodePudding user response:
Use basic interfaces for polymorphism.
type character interface {
Move()
Pos() [2]int
}
type Knight struct {
pos [2]int
}
func (K *Knight) Move() {
fmt.Println("Moving Kinght...")
}
func (k *Knight) Pos() [2]int { return k.pos }
type King struct {
pos [2]int
}
func (k *King) Move() {
fmt.Println("Moving King...")
}
func (k *King) Pos() [2]int { return k.pos }
The following statement compiles with this changes:
characters := []character{&Knight{}, &King{}}
Also, you probably want pointer receivers as in this example.