PHP code example of laxity7 / glicko2

1. Go to this page and download the library: Download laxity7/glicko2 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laxity7 / glicko2 example snippets


use laxity7\glicko2\Player;
use App\UserRating;

class UserRating
{
    public int $user_id;
    public float $rating;
    public float $rating_deviation;
    public float $rating_volatility;
}

class Repository
{
    public function getUserRating(int $userId)
    {
        $userRating = $this->findInDbFromId($userId);
        if (!$userRating) {
            $userRating = $this->createUserRating($userId);
        }
        return $userRating;
    }
    
    public function createUserRating(int $userId)
    {
        $player = new Player();
        $userRating = new UserRating();
        $userRating->user_id = $userId;
        $userRating->rating = $player->getRating();
        $userRating->rating_deviation = $player->getRatingDeviation();
        $userRating->rating_volatility = $player->getRatingVolatility();
    
        $this->saveToDb($userRating);
        
        return $userRating;
    }
    
    public function updateRating(int $userId, Player $player)
    {
        $userRating = $this->getUserRating($userId);
        $userRating->rating = $player->getRating();
        $userRating->rating_deviation = $player->getRatingDeviation();
        $userRating->rating_volatility = $player->getRatingVolatility();

        $this->saveToDb($userRating);
    }
}

use laxity7\glicko2\MatchGame;
use laxity7\glicko2\MatchCollection;
use laxity7\glicko2\Player;

$repository = new Repository();

$userRating1 = $repository->getUserRating(1);
$userRating2 = $repository->getUserRating(2);

$player1 = new Player($userRating1->rating, $userRating1->rating_deviation, $userRating1->rating_volatility);
$player2 = new Player($userRating2->rating, $userRating2->rating_deviation, $userRating2->rating_volatility);
//$player2 = new Player(); available defaults for new player

// match chain
$match1 = new MatchGame($player1, $player2, 1, 0);
$match1->calculate(); // The calculation method does not return anything, it only calculates and changes the rating of players

$match2 = new MatchGame($player1, $player2, 3, 2);
$match2->calculate();

// or match collection
$matchCollection = new MatchCollection();
$matchCollection->addMatch(new MatchGame($player1, $player2, 1, 0));
$matchCollection->addMatch(new MatchGame($player1, $player2, 3, 2));
$matchCollection->calculate();

// just get a new ratings
$newPlayer1Rating = $player1->getRating();
$newPlayer2Rating = $player2->getRating();

// for example, save to the database
$repository->updateRating(1, $player1);
$repository->updateRating(2, $player2);