FAQ - RumenDamyanov/go-chess GitHub Wiki

Frequently Asked Questions (FAQ)

Common questions and answers about the go-chess library.

General Questions

What is go-chess?

go-chess is a complete chess engine and API library written in Go. It provides:

  • Full chess rule implementation
  • Multiple AI opponents (traditional algorithms + LLM-powered)
  • RESTful API for web applications
  • WebSocket support for real-time games
  • Game persistence in PGN/FEN formats

What makes it different from other chess libraries?

  1. LLM Integration: Unique support for AI opponents powered by GPT-4, Claude, Gemini, etc.
  2. Conversational AI: Chat with your AI opponents about moves and strategy
  3. Production Ready: Built for real-world applications with proper error handling
  4. Modern Go: Uses modern Go practices and clean architecture
  5. Complete API: Full HTTP/WebSocket API for frontend integration

Is it suitable for production use?

Yes! The library is designed for production use with:

  • Comprehensive error handling
  • Performance optimization
  • Security best practices
  • Extensive testing
  • CI/CD pipeline
  • Documentation

Installation & Setup

What Go version do I need?

Go 1.21 or later is required.

How do I install go-chess?

go mod init your-project
go get github.com/rumendamyanov/go-chess

Do I need API keys to use it?

API keys are only required for LLM AI features. Traditional AI opponents work without any external dependencies.

Which LLM providers are supported?

  • OpenAI (GPT-4, GPT-3.5)
  • Anthropic (Claude 3.5, Claude 3)
  • Google (Gemini 1.5 Pro)
  • xAI (Grok Beta)
  • DeepSeek (DeepSeek Chat)

Features & Functionality

Can I use it without AI opponents?

Absolutely! The core chess engine works independently:

game := engine.NewGame()
move, _ := game.ParseMove("e4")
game.MakeMove(move)

How accurate is the chess implementation?

The engine implements all standard chess rules including:

  • All piece movements
  • Castling (kingside and queenside)
  • En passant capture
  • Pawn promotion
  • Check and checkmate detection
  • Stalemate and draw conditions
  • Fifty-move rule
  • Threefold repetition

Can I build a chess website with this?

Yes! The library includes a complete HTTP API:

server := api.NewServer(config.Default())
r := gin.Default()
server.SetupRoutes(r)
r.Run(":8080")

Does it support real-time multiplayer?

Yes, through WebSocket connections:

const ws = new WebSocket('ws://localhost:8080/ws/games/1');
ws.onmessage = (event) => {
    const gameUpdate = JSON.parse(event.data);
    updateBoard(gameUpdate.board);
};

AI Questions

How good are the AI opponents?

AI strength varies by engine:

  • Random AI: Beginner level, makes random legal moves
  • Minimax AI: Intermediate level, decent tactical play
  • LLM AI: Variable - from casual to near-expert depending on provider/model

Can I adjust AI difficulty?

Yes, all AI engines support difficulty levels:

ai := ai.NewMinimaxAI(ai.DifficultyHard)
ai.SetDifficulty(ai.DifficultyEasy) // Change dynamically

How does LLM AI work?

LLM AI opponents:

  1. Analyze the current board position
  2. Generate strategic moves using language models
  3. Provide conversational responses about the game
  4. Fall back to traditional AI if LLM fails

Which LLM provider should I choose?

Recommendations by use case:

  • Learning/Teaching: Anthropic Claude (detailed explanations)
  • Casual Games: OpenAI GPT-4 (balanced performance)
  • Entertainment: xAI Grok (witty commentary)
  • Budget: DeepSeek (cost-effective)
  • Speed: Google Gemini (fast responses)

Can AI explain its moves?

Yes, with LLM AI:

// Get move
move, _ := llmAI.GetBestMove(ctx, game)

// Get explanation
explanation, _ := llmAI.Chat(ctx, "Why did you play that move?", game)

Technical Questions

How do I handle errors?

The library uses standard Go error handling:

move, err := game.ParseMove("e4")
if err != nil {
    // Handle parse error
}

if err := game.MakeMove(move); err != nil {
    // Handle move error
}

Is it thread-safe?

The core engine is not thread-safe by design (for performance). Use mutexes for concurrent access:

var gameMutex sync.RWMutex

func makeMove(move engine.Move) error {
    gameMutex.Lock()
    defer gameMutex.Unlock()
    return game.MakeMove(move)
}

How do I persist games?

Games can be saved/loaded in standard formats:

// Save as PGN
pgn := game.PGN()
ioutil.WriteFile("game.pgn", []byte(pgn), 0644)

// Save as FEN
fen := game.FEN()

// Load from PGN
game, err := engine.NewGameFromPGN(pgnString)

// Load from FEN
game, err := engine.NewGameFromFEN(fenString)

What about performance?

Performance characteristics:

  • Move Generation: ~50,000 moves/second
  • Position Evaluation: ~10,000 positions/second
  • Memory Usage: <10MB for typical games
  • AI Response: 50ms-5s depending on difficulty

Can I extend the AI system?

Yes! Implement the Engine interface:

type MyCustomAI struct {
    difficulty Difficulty
}

func (ai *MyCustomAI) GetBestMove(ctx context.Context, game *engine.Game) (engine.Move, error) {
    // Your AI logic here
}

func (ai *MyCustomAI) GetDifficulty() Difficulty { return ai.difficulty }
func (ai *MyCustomAI) SetDifficulty(d Difficulty) { ai.difficulty = d }

Usage Patterns

How do I create a simple game loop?

func playGame() {
    game := engine.NewGame()
    ai := ai.NewRandomAI()

    for game.Status() == engine.StatusInProgress {
        if game.CurrentPlayer() == engine.White {
            // Human move
            fmt.Print("Your move: ")
            var notation string
            fmt.Scanln(&notation)

            move, err := game.ParseMove(notation)
            if err == nil {
                game.MakeMove(move)
            }
        } else {
            // AI move
            move, _ := ai.GetBestMove(context.Background(), game)
            game.MakeMove(move)
            fmt.Printf("AI: %s\n", move.String())
        }
    }
}

How do I analyze positions?

// Get all legal moves
moves := game.LegalMoves()

// Check if in check
inCheck := game.IsInCheck(game.CurrentPlayer())

// Evaluate position
eval := game.Evaluate()

// Get material count
material := game.MaterialCount()

How do I implement move validation?

func validateAndMakeMove(game *engine.Game, notation string) error {
    // Parse move
    move, err := game.ParseMove(notation)
    if err != nil {
        return fmt.Errorf("invalid notation: %w", err)
    }

    // Check if legal
    if !game.IsLegalMove(move) {
        return fmt.Errorf("illegal move: %s", notation)
    }

    // Check game state
    if game.Status() != engine.StatusInProgress {
        return fmt.Errorf("game is over")
    }

    // Make move
    return game.MakeMove(move)
}

API Questions

What endpoints are available?

Core endpoints:

  • POST /api/games - Create game
  • GET /api/games/{id} - Get game state
  • POST /api/games/{id}/moves - Make move
  • POST /api/games/{id}/ai-move - Get AI move

LLM endpoints:

  • POST /api/games/{id}/chat - Chat with AI
  • POST /api/games/{id}/react - Get AI reaction

How do I make API requests?

# Create game
curl -X POST http://localhost:8080/api/games

# Make move
curl -X POST http://localhost:8080/api/games/1/moves \
  -H "Content-Type: application/json" \
  -d '{"from": "e2", "to": "e4"}'

# Chat with AI
curl -X POST http://localhost:8080/api/games/1/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Good move!", "provider": "openai"}'

How do I handle CORS for web frontends?

CORS is enabled by default in the API server. For custom setups:

r.Use(func(c *gin.Context) {
    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
    c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
    c.Next()
})

Can I customize the API server?

Yes! The server is highly customizable:

cfg := config.Default()
cfg.Server.Port = 9000
cfg.Server.Host = "0.0.0.0"

server := api.NewServer(cfg)
// Add custom middleware, routes, etc.

Cost & Licensing

Is go-chess free?

Yes! It's open source under the MIT license.

What about LLM API costs?

LLM providers charge for API usage:

  • OpenAI: ~$0.01-0.03 per move (depending on model)
  • Anthropic: ~$0.01-0.02 per move
  • Google: ~$0.001-0.01 per move
  • xAI: Pricing varies
  • DeepSeek: Most cost-effective option

Can I use it commercially?

Yes! The MIT license allows commercial use.

Troubleshooting

My AI is too slow

Solutions:

  1. Reduce difficulty level
  2. Set time limits: ai.SetMaxThinkTime(3 * time.Second)
  3. Use faster AI for real-time play: ai.NewRandomAI()

LLM requests are failing

Common causes:

  1. Invalid API key
  2. Rate limiting
  3. Network timeouts
  4. Model not found

See Troubleshooting for detailed solutions.

Getting compilation errors

Check:

  1. Go version (need 1.21+)
  2. Module initialization: go mod init && go mod tidy
  3. Import paths are correct

Contributing

How can I contribute?

Ways to contribute:

  1. Report bugs
  2. Suggest features
  3. Submit pull requests
  4. Improve documentation
  5. Add examples

Where do I report bugs?

GitHub Issues: github.com/rumendamyanov/go-chess/issues

Can I add new AI engines?

Yes! Implement the Engine interface and submit a PR.

How do I add new LLM providers?

  1. Add provider constants
  2. Implement API client
  3. Add configuration options
  4. Submit PR with tests

Future Plans

What features are planned?

Upcoming features:

  • Opening book integration
  • Endgame tablebase support
  • Advanced position analysis
  • Tournament management
  • More LLM providers
  • Mobile SDK

How often is it updated?

Regular updates include:

  • Bug fixes
  • Performance improvements
  • New features
  • Security updates
  • Dependency updates

Can I request features?

Yes! Create feature requests on GitHub Issues or Discussions.

Getting Help

Where can I get support?

Resources:

  • Documentation: This wiki
  • Examples: examples/ directory
  • GitHub Issues: Bug reports and questions
  • GitHub Discussions: Community discussion
  • Code: Well-commented source code

How do I stay updated?

  • Watch the GitHub repository
  • Check the Changelog
  • Follow release notifications

Still have questions? Create an issue on GitHub or start a discussion. The community is happy to help! ♟️