Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Elo Laravel Package

avoo/elo

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require avoo/elo
    

    Ensure composer.json includes the package under require.

  2. Basic Usage Import the core class and initialize with default settings:

    use Avoo\Eloquent\EloCalculator;
    
    $eloCalculator = new EloCalculator();
    
  3. First Calculation Simulate a match between two players (e.g., Player A with 1500 Elo vs. Player B with 1400 Elo):

    $result = $eloCalculator->calculate(1500, 1400, true); // true = Player A wins
    echo $result['newEloA']; // Updated Elo for Player A
    
  4. Key Files

    • src/EloCalculator.php: Core logic (K-factor, formula overrides).
    • tests/: Unit tests for edge cases (e.g., draws, invalid inputs).

Implementation Patterns

Core Workflows

  1. Match Result Handling

    • Win/Loss: Pass true/false for the winner.
    • Draw: Use null or a dedicated method if extended:
      $eloCalculator->calculate(1500, 1400, null); // Draw logic (default: split points)
      
  2. Custom K-Factors Override the default K-factor (e.g., 32 for beginners, 16 for experts):

    $eloCalculator = new EloCalculator(16); // Initialize with custom K
    
  3. Batch Processing Loop through match results for efficiency:

    $matches = [
        ['playerA' => 1500, 'playerB' => 1400, 'winner' => 'A'],
        ['playerA' => 1600, 'playerB' => 1550, 'winner' => 'B'],
    ];
    
    foreach ($matches as $match) {
        $result = $eloCalculator->calculate($match['playerA'], $match['playerB'], $match['winner'] === 'A');
        // Store $result in DB
    }
    
  4. Integration with Eloquent Attach to a Player model’s afterSave or afterUpdate:

    // Player.php
    public function updateElo($winner, $opponentElo) {
        $eloCalculator = new EloCalculator();
        $newElo = $eloCalculator->calculate($this->elo, $opponentElo, $winner)->newElo;
        $this->elo = $newElo;
        $this->save();
    }
    
  5. Testing Mock the calculator in unit tests:

    $eloCalculator = $this->createMock(EloCalculator::class);
    $eloCalculator->method('calculate')
        ->willReturn(['newEloA' => 1600, 'newEloB' => 1300]);
    

Gotchas and Tips

Pitfalls

  1. Floating-Point Precision Elo calculations may yield floating-point results (e.g., 1500.42). Round to integers if required:

    $newElo = ceil($result['newEloA']); // or floor()/round()
    
  2. K-Factor Misconfiguration

    • Too High: Rapid Elo swings (e.g., K=100 for ranked games).
    • Too Low: Stagnant ratings (e.g., K=1 for competitive play). Tip: Start with K=32 for balanced adjustments.
  3. Draw Handling Default behavior splits the expected point difference equally. Override in a subclass:

    class CustomEloCalculator extends EloCalculator {
        protected function handleDraw($eloA, $eloB) {
            return [
                'newEloA' => $eloA + 0.5, // Custom logic
                'newEloB' => $eloB + 0.5,
            ];
        }
    }
    
  4. Negative Elo The library doesn’t enforce minimums. Validate inputs:

    if ($eloA < 0 || $eloB < 0) {
        throw new \InvalidArgumentException("Elo cannot be negative");
    }
    
  5. Thread Safety The calculator is stateless but ensure thread safety in concurrent environments (e.g., queues):

    // Safe for parallel jobs
    $eloCalculator = new EloCalculator();
    

Debugging Tips

  • Log Intermediate Values Extend the class to log probabilities:

    class DebugEloCalculator extends EloCalculator {
        public function calculate($eloA, $eloB, $winner) {
            $result = parent::calculate($eloA, $eloB, $winner);
            \Log::debug("Probabilities: A={$this->getProbability($eloA, $eloB)}%, B=" . (100 - $this->getProbability($eloA, $eloB)) . "%");
            return $result;
        }
    }
    
  • Unit Test Edge Cases Test with:

    • Identical Elo values (1500 vs 1500).
    • Extreme Elo differences (50 vs 2500).
    • Null/undefined inputs.

Extension Points

  1. Custom Formulas Override calculateExpectedScore() for non-standard Elo variants:

    protected function calculateExpectedScore($eloA, $eloB) {
        return 1 / (1 + pow(10, ($eloB - $eloA) / 400)); // Standard Elo
        // OR: Custom formula (e.g., Glicko-2)
    }
    
  2. Event Dispatching Trigger events after calculations (e.g., elo:updated):

    use Illuminate\Support\Facades\Event;
    
    $eloCalculator = new EloCalculator();
    $result = $eloCalculator->calculate(1500, 1400, true);
    Event::dispatch(new EloUpdated($result));
    
  3. Database Storage Use Laravel’s observers or accessors to auto-update Elo:

    // Player.php
    public function getEloAttribute($value) {
        return $this->attributes['elo'] ?? 1200; // Default
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator