This commit is contained in:
TorstenS 2020-06-09 10:01:36 +02:00
parent 9441631dd4
commit 8e704e7afa
4221 changed files with 1 additions and 544259 deletions

View file

@ -1,841 +0,0 @@
<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\Season;
use App\Round;
use App\User;
use App\Leagues\LeagueMember;
use DB;
use Log;
use App\MyClasses;
class League extends Model
{
const RANK_LEAGUE1 = 1;
const RANK_LEAGUE2 = 2;
const RANK_LEAGUE3 = 3;
const RANK_QUALIFICATION = 4;
protected $table ='leagues';
protected $fillable = [
'id','season_id','is_qualification','rank','subrank','start_round_id','round_count','name'
];
//
public static function neededLeagues($member_count, $round_count) {
$max_members_per_league=22;
if ( $round_count < $max_members_per_league-1 ) { $max_members_per_league = $round_count+1; }
if ($member_count <= $max_members_per_league) return $member_count;
$neededLeagues = intdiv($member_count, $max_members_per_league);
if ( $member_count - $max_members_per_league * $neededLeagues ) {
$neededLeagues+=1;
}
return $neededLeagues;
}
public static function getMemberCount($league_id) {
$members = DB::table('leagues_members')->where('league_id','=',$league_id)->get();
return sizeof($members);
}
public static function getNames() {
$season = Season::getCurrent();
$leagues = League::where('season_id','=',$season->id)->orderBy('rank')->orderBy('name')->get();
$leagueNames = array();
foreach($leagues as $league) {
$leagueNames[$league->id] = $league->name;
}
return $leagueNames;
}
public static function getStartRoundId($leagueId)
{
$league = League::where('id','=',$leagueId)->first();
return $league->start_round_id;
}
public static function cmpScore($score1, $score2) {
// [0] = user-id
// [1] = league_score
// [4] = rank
$_score1 = $score1[1];
$goals1 = $score1[2];
$cGoals1 = $score1[3];
$rank1 = -1;
if (array_key_exists(4, $score1 )) { $rank1 = $score1[4]; }
$_score2 = $score2[1];
$goals2 = $score2[2];
$cGoals2 = $score2[3];
$rank2 = -1;
if (array_key_exists(4, $score2 )) {$rank2 = $score2[4]; }
$diff1 = $goals1-$cGoals1;
$diff2 = $goals2-$cGoals2;
if ($rank1 > $rank2) return true;
if ($rank1 < $rank2) return false;
if ($_score1 == $_score2) {
if ($diff1==$diff2) {
if ($goals1 == $goals2) {
return $cGoals1 > $cGoals2;
}
return ( $goals1 < $goals2 );
}
return ($diff1<$diff2);
}
return ($_score1 < $_score2);
}
// Funktioniert nur auf bereits sortierter Liste, nur für Selektion Gruppe 3 Auf & Abstieg
public static function cmpScoreForPos($score1, $score2) {
// [0] = user-id
// [4] = rank
$_score1 = $score1[1];
$goals1 = $score1[2];
$cGoals1 = $score1[3];
$rank1 = $score1[4];
$pos1 = $score1[5];
$_score2 = $score2[1];
$goals2 = $score2[2];
$cGoals2 = $score2[3];
$rank2 = $score2[4];
$pos2 = $score2[5];
$diff1 = $goals1-$cGoals1;
$diff2 = $goals2-$cGoals2;
if ($rank1 > $rank2) return true;
if ($rank1 < $rank2) return false;
if ($pos1 > $pos2) return true;
if ($pos1 < $pos2) return false;
if ($_score1 == $_score2) {
if ($diff1==$diff2) {
if ($goals1 == $goals2) {
return $cGoals1 > $cGoals2;
}
return ( $goals1 < $goals2 );
}
return ($diff1<$diff2);
}
return ($_score1 < $_score2);
}
public static function getRanking($rank, $seasonId=-1) {
$season = Season::getCurrent();
if ($seasonId > -1) { $season=Season::where('id','=',$seasonId)->first(); };
$leagues = League::where('rank','=',$rank)->where('season_id','=', $season->id)->orderBy('id')->get();
$leagueScores=array();
foreach($leagues as $league) {
$memberIds = LeagueMember::getMembers($league->id);
$memberScores =array();
foreach($memberIds as $memberId) {
$tpl=array();
$tpl[0]=$memberId;
$tpl[1]=0; // league_score
$tpl[2]=0; // goals
$tpl[3]=0; // countergoals
$memberScores[$memberId] = $tpl;
}
$lastLockedRoundId=Round::getLastLockedRoundId();
Log::info("LASTLOCKKEDROUNDID=".$lastLockedRoundId);
$matches=Match::getMatchResults($league->id,-1);
foreach ($matches as $match) {
if (Round::isCompleted($match->round_id) || $match->round_id==$lastLockedRoundId ) {
$memberScores[$match->user1_id][1] += $match->user1_league_score;
error_log("+++ ".$match->user1_id." +".$match->user1_league_score);
$memberScores[$match->user1_id][2] += $match->user1_rankscore; // goals
$memberScores[$match->user1_id][3] += $match->user2_rankscore; // countergoals
$memberScores[$match->user2_id][1] += $match->user2_league_score;
error_log("+++ ".$match->user2_id." +".$match->user2_league_score);
$memberScores[$match->user2_id][2] += $match->user2_rankscore; // goals
$memberScores[$match->user2_id][3] += $match->user1_rankscore; // countergoals
}
}
usort($memberScores, array('App\Leagues\League','cmpScore'));
$leagueScores[$league->id]=$memberScores;
error_log("League::getRanking leagueid / userid / score");
foreach ($memberScores as $entry) {
error_log($league->id." / ".$entry[0]." / ".$entry[1]);
}
error_log("---");
}
return $leagueScores;
}
// Für Auf/Abstiegsberechnung - wird auf previous Season angewendet.
// getUnifiedRanking bezieht sich (nur) auf Gruppen-Übergreifende Listung (also alle Untergruppen)
// Rank = -1 bedeutet über alle Ranks (benötigt für Auf- und Abstieg über alle Ligen)
public static function getUnifiedRanking($rank, $seasonId=-1) {
//Log::info("getUnified Ranking [last season], rank=".$rank." seasonId=".$seasonId);
$leagueScores = League::getRanking($rank, $seasonId);
$unifiedScores = array();
foreach($leagueScores as $leagueId => $singleLeagueScores) {
foreach ($singleLeagueScores as $placeNr => $singleLeagueScore) {
$userId=$singleLeagueScores[$placeNr][0];
$scoreWithPos=$singleLeagueScores[$placeNr];
$scoreWithPos[4]=$placeNr+1;
$unifiedScores[$userId]=$scoreWithPos;
}
}
usort($unifiedScores,array('App\Leagues\League','cmpScore'));
//Log::info("getUnifiedRanking result, $rank=".$rank.", SeasonId=".$seasonId);
//Log::info($unifiedScores);
return $unifiedScores;
}
// Nur für Auf und Abstiegsberechnung.
// Schreibt den zukünftigen Rank auf Index4
public static function getTotalRankingOverall($seasonId=-1) {
$a=new MyClasses\TimeLogger("League::getTotalRankingOverall (seasonId=".$seasonId.")");
Log::info($a->getStartMessage());
$userNames = User::getNames();
$totalRanking=array();
$hasRank4 = false;
foreach([1,2,3,4] as $rank) {
foreach (League::getUnifiedRanking($rank, $seasonId) as $rankEntry) {
// Tuple: [0] = userId, [1] = league_score [2] = goals, [3] = counter_goals [4] = LigaPos
$tpl = array();
$tpl[0] = $rankEntry[0]; // userId
$tpl[1] = $rankEntry[1]; // league_score
$tpl[2] = $rankEntry[2]; // goals
$tpl[3] = $rankEntry[3]; // countergoals
$tpl[4] = $rank; // league_rank (1,2,3, 4=quali)
$tpl[5] = $rankEntry[4]; // league_pos (for multiple leagues per rank, usually ranks 3 and 4)
if ($rank==4) { $hasRank4=true;}
// only add to list if user has paid for season
if (User::is_season_paid($tpl[0])=="Ja") {
array_push($totalRanking, $tpl);
}
}
}
usort($totalRanking, array('App\Leagues\League','cmpScore'));
usort($totalRanking, array('App\Leagues\League','cmpScoreForPos')); // Dieser Sort funktioniert nur auf bereits sortierter Liste !! Nur für GruppenRank=3
// Neuen Rang auf Index 4 schreiben
foreach ($totalRanking as $index => $entry) {
$rank=3;
if ($index<44) { $rank=2; }
if ($index<22) { $rank=1; }
$totalRanking[$index][4]=$rank;
}
// kein Rank4 ==> Ligaspiel ==> Auf & Abstieg wird angewendet.
if ($hasRank4) {
Log::info("Rank4 gesetzt, Quali, keine Vorsaison, Auf/Abstieg wird übersprungen");
}else {
Log::info("Rank4 nicht gesetzt, keine Quali, Auf/Abstieg wird berechnet");
// Liga 1/2: Swap rank 17-22 <> 23-28 ==> index 16-21 to rank=2, index 22-27 to rank=1
// Liga 2/3: Swap rank 39-44 <> 45-50 ==> index 38-43 to rank=3, index 44-49 to rank=2
$totalRanking[16][4]=2;
$uid=$totalRanking[16][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[17][4]=2;
$uid=$totalRanking[17][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[18][4]=2;
$uid=$totalRanking[18][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[19][4]=2;
$uid=$totalRanking[19][0];
Log::info("Abstieg in Liga 2: ["+$uid+"] ".$userNames[$uid]);
$totalRanking[20][4]=2;
$uid=$totalRanking[20][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[21][4]=2;
$uid=$totalRanking[21][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[22][4]=1;
$uid=$totalRanking[22][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[23][4]=1;
$uid=$totalRanking[23][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[24][4]=1;
$uid=$totalRanking[24][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[25][4]=1;
$uid=$totalRanking[25][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[26][4]=1;
$uid=$totalRanking[26][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[27][4]=1;
$uid=$totalRanking[27][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[38][4]=3;
$uid=$totalRanking[38][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[39][4]=3;
$uid=$totalRanking[39][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[40][4]=3;
$uid=$totalRanking[40][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[41][4]=3;
$uid=$totalRanking[41][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[42][4]=3;
$uid=$totalRanking[42][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[43][4]=3;
$uid=$totalRanking[43][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[44][4]=2;
$uid=$totalRanking[44][0];
Log::info("Aufstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[45][4]=2;
$uid=$totalRanking[45][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[46][4]=2;
$uid=$totalRanking[46][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[47][4]=2;
$uid=$totalRanking[47][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[48][4]=2;
$uid=$totalRanking[48][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[49][4]=2;
$uid=$totalRanking[49][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
usort($totalRanking, array('App\Leagues\League','cmpScore'));
}
// HACK TO BE REMOVED: SET POSITIONS MANUALLY 2018-08
/*
foreach ($totalRanking as $index => $entry) {
$uid=$totalRanking[$index][0];
if ($uid==65 or $uid==80 or $uid==84 or $uid==3) {
$totalRanking[$index][4]=3;
}
if ($uid==68 or $uid==32 or $uid==9 or $uid==74) {
$totalRanking[$index][4]=2;
}
}
usort($totalRanking, array('App\Leagues\League','cmpScore'));
*/
// END OF HACK
Log::info($a->getEndMessage());
//error_log($a->getEndMessage());
return $totalRanking;
}
public static function getNewUsers($seasonId=-1) {
$users=User::getActives($seasonId);
$previousSeason=Season::getPrevious($seasonId);
$old_users=User::getActives($previousSeason->id);
// Structure of unified list entry
/*
$tpl = array();
$tpl[0] = $rankEntry[0]; // userId
$tpl[1] = $rankEntry[1]; // league_score
$tpl[2] = $rankEntry[2]; // goals
$tpl[3] = $rankEntry[3]; // countergoals
$tpl[4] = $rank; // league_rank (1,2,3, 4=quali)
$tpl[5] = $rankEntry[4]; // league_pos (for multiple leagues per rank, usually ranks 3 and 4)
*/
$new_users=array();
foreach($users as $user) {
$exists=0;
foreach($old_users as $old_user) {
if ($old_user->id == $user->id) { $exists=1;}
}
if (!$exists) {
if (User::payment_date($user->id, $seasonId)) {
$entry = [$user->id,0,0,0,3,0];
array_push($new_users, $entry);
}
}
}
return $new_users;
}
// ausfaktoriert aus LeaguesController::createLeagues()
// TODO: $round_count ist nur im Quali-Modus relevant und steuert, wieviele Quali-Gruppen benötigt werden.
// TODO: Sobald es Liga1 und Liga2 gibt, wird der round_count immer 21 sein, da Liga1 und Liga2 auf
// TODO: 22 Mitspieler festgelegt sind.
public static function createLeagues($start_round_id, $round_count) {
Log::info("Leagues\League::createLeagues, start_round_id=".$start_round_id.", round_count=".$round_count);
$currentSeason=Season::getCurrent();
$previousSeason=Season::getPrevious();
$userNames = User::getNames();
// Eventuell vorhandene Ligen loeschen
$leagues=League::where('season_id','=',$currentSeason->id)->get();
if ($leagues) {
foreach ($leagues as $league) {
DB::table('leagues_matches')->where('league_id', '=', $league->id)->delete();
DB::table('leagues_members')->where('league_id', '=', $league->id)->delete();
DB::table('leagues')->where('id', '=', $league->id)->delete();
}
}
$active_member_count=sizeof(User::getActives());
Log::info("Aktive Spieler: ".$active_member_count);
$neededLeagues3 = League::neededLeagues($active_member_count, $round_count);
Log::info("Benötigte Liga-Gruppen: ".$neededLeagues3);
$league_ids=array();
//TODO: Wenn es keine Vorsaison gibt -> Qualifikation
//TODO: Ansonsten: Standard-Ligen (1,2,3) erzeugen. Liga 1 und 2 sind auf 22 Spieler festgelegt.
if (!$previousSeason) {
// Alle Spieler werden gleichmässig auf Qualifikationsgruppen aufgeteilt
// Dieser Modus wird gewählt, wenn es keine Vorsaison gibt, es also
// die erste Saison im System ist.
Log::info("League::createLeagues => No previous season detected.");
for ($league_nr=1; $league_nr<=$neededLeagues3; $league_nr+=1) {
$league = League::create([
'is_qualification' => true,
'name' => 'Qualifikationsgruppe '.$league_nr,
'rank' => '4',
'subrank' => $league_nr,
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league->save();
$league_ids[$league_nr-1] = $league->id;
}
// Distribute members
$users = User::getActives();
shuffle($users);
$league_index=0;
Log::info("Distributing Members between groups");
while(sizeof($users)>0) {
$user = array_pop($users);
$leagueMember = LeagueMember::create([
'user_id' => $user->id,
'league_id' => $league_ids[$league_index]
]);
$leagueMember->save();
error_log("Saving user_id ".$user->id);
$league_index+=1;
if (sizeof($league_ids)==$league_index) { $league_index=0; }
}
} else {
// Es gibt eine Vorsaison.
// - 1.) Ligen erzeugen
// - 2.) unified Liste bauen
// - 3.) Wenn Vorsaison keine Quali war, dann Auf & Abstieg umsetzen ( unfified Liste als Basis )
// - 4.) Member den Ligen zuordnen
Log::info("League::createLeagues => Previous season detected. Creating Leagues 1, 2 and 3");
// Erzeugung der Ligen
$createdLeagues=array();
$neededLeagues3=0;
$league_size1= min(22,$active_member_count);
$league1 = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 1',
'rank' => '1',
'subrank' => '1',
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
array_push($createdLeagues, $league1);
$league_size2=min(22,$active_member_count - $league_size1);
if ($league_size2>0) {
$league2 = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 2',
'rank' => '2',
'subrank' => '1',
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
array_push($createdLeagues, $league2);
$league_size3 = $active_member_count - $league_size1 - $league_size2;
// Make neededLeagues3 visible outside of scope
$neededLeagues3=-1;
if ($league_size3>0) {
$neededLeagues3 = League::neededLeagues($league_size3, $round_count);
// Wenn es mehr als eine Gruppe ist, mpssen
if ($neededLeagues3>1) {
}
for ($league_nr=1; $league_nr<=$neededLeagues3; $league_nr+=1) {
$league = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 3, Gruppe '.$league_nr,
'rank' => '3',
'subrank' => $league_nr,
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league->save();
array_push($createdLeagues,$league);
}
}
Log::info("League::createLeagues Creating unified List from previous season (i call League::getTotalRankingOverall)");
$unifiedList = League::getTotalRankingOverall($previousSeason->id); // WICHTIG !! getTotalRankingOverall implentiert Auf- und Abstieg !!
Log:info("League::createLeagues Unified List:");
$userNames = User::getNames();
$unifiedList2=array(); // We will only transfer users over to here that have paid the current season and are not deleted.
$count=0;
foreach($unifiedList as $listEntry) {
$userId = $listEntry[0];
$leagueScore=$listEntry[1];
if (User::is_season_paid($userId) && !User::isDeleted($userId)) {
$count+=1;
array_push($unifiedList2, $listEntry);
Log::info($count.".) [".$userId."] ".$userNames[$userId]." ".$leagueScore." Punkte");
} else {
Log::info($count.".) [".$userId."] ".$userNames[$userId]." [DELETED]");
}
}
$unifiedList = $unifiedList2;
// Jetzt neue Spieler hinzufügen, die letzte Saison noch nicht dabei waren, und deshalb in getTotalRankingOverall nicht enthalten sind.
Log::info("League::createLeagues Adding new users not within previous season");
foreach( League::getNewUsers() as $entry) {
array_push($unifiedList, $entry);
$userId=$entry[0];
Log::info("adding new user not in previous season: ( [".$userId."] ".$userNames[$userId]." )");
}
// Wenn es für Liga 3 mehr als eine Gruppe gibt, dann die Reihenfolge der Members randomisieren.
if ($neededLeagues3>1) {
$numberOfSwaps=50;
// Structure of unified list entry
/*
$tpl = array();
$tpl[0] = $rankEntry[0]; // userId
$tpl[1] = $rankEntry[1]; // league_score
$tpl[2] = $rankEntry[2]; // goals
$tpl[3] = $rankEntry[3]; // countergoals
$tpl[4] = $rank; // league_rank (1,2,3, 4=quali)
$tpl[5] = $rankEntry[4]; // league_pos (for multiple leagues per rank, usually ranks 3 and 4)
*/
Log::info("League 3 entries before shuffling:");
foreach($unifiedList as $entry) {
if ($entry[4]==3) {
Log::info ("(".$entry[0].") ".$userNames[$entry[0]]);
}
}
$league3entries=array();
foreach($unifiedList as $pos => $entry) {
if ($entry[4]==3) {
array_push($league3entries, $entry);
}
}
shuffle($league3entries);
$pos=0;
foreach ( $unifiedList as $key => $entry) {
if ($entry[4]==3) {
$unifiedList[$key] = $league3entries[$pos];
$pos += 1;
}
}
Log::info("League 3 entries after shuffling:");
foreach($unifiedList as $entry) {
if ($entry[4]==3) { Log::info ("(".$entry[0].") ".$userNames[$entry[0]]); }
}
}
$currentCount = 1;
$nr=1;
$leagueNr=1;
$neededSize3=0;
$subLeague=1; // for rank 3 leagues only
$leagueCount=1;
$leagueIndex=0;
Log::info("League::createLeagues unified list size= ".sizeof($unifiedList));
foreach($unifiedList as $entry) {
if ($nr==23) { $leagueNr=2; $leagueCount=1; $leagueIndex=1; }
if ($nr==45) {
$leagueNr=3; $leagueCount=1; $leagueIndex=2;
$neededSize3=intdiv(($active_member_count-44),$neededLeagues3); // $neededLeagues = needed Groups for rank 3 leagues
if ( ($active_member_count-44) % 2) {
$neededSize3+=1;
}
Log::info("League::createLeagues Needed min/switch size for rank 3 leagues: ".$neededSize3);
}
if ($nr>45 && $leagueCount > $neededSize3) {
$subLeague+=1;
$leagueCount=1;
$leagueIndex+=1;
}
Log::info("League::createLeagues "."#".$leagueCount." Liga ".$leagueNr."-".$subLeague.") ".$nr." ".$entry[0]." (".$userNames[$entry[0]].")");
$league=$createdLeagues[$leagueIndex];
$leagueMember = LeagueMember::create([
'user_id' => $entry[0],
'league_id' => $league->id
]);
Log::Info("(".$entry[0].") ".$userNames[$entry[0]]." => leagueIndex=".$leagueIndex);
$leagueMember->save();
$leagueCount+=1;
$nr++;
}
}
}
}
// Aktuelle Liga-Zuordnung auf Basis des Rangs in der letzten Liga
// Oder des Rangs in der Qualifikation
// oder erstellung des Quali Rangs wenn es keine previous Season gibt.
// Liga-Zugehörigkeit festlegen. Setzt voraus, dass die Ligen bereits erzeugt wurden.
public static function setLeagueForPlayers()
/*
* setLeagueForPlayers__NEW_QUALIFICATION case1
* setLeagueForPlayers__FROM_QUALIFICATION case2
* setLeagueForPlayers__FROM_LEAGUES case3
*/
{
$previousSeason = Season::getPrevious();
$currentSeason = Season::getCurrent();
$users = User::getActives();
if (!$previousSeason) {
// case 1: first season ever, no previous season exists, qualification (league-rank=4)
} elseif (Season::hasQualification($previousSeason->id)){
// case 2: previous season was qualification season (rank 4)
} else { /*case 3 - default: determine league-ranks 1,2,3 from previous Season rank verwenden*/
}
// 2 Möglichkeiten:
// 1.) previousSeason hat rank=4 => Qualification Round
// 2.) sonst aus .
$usersLastSeason = User::getActives($previousSeason->id);
$league1 = League::getUnifiedRanking(1, $previousSeason->id);
$league2 = League::getUnifiedRanking( 2, $previousSeason->id);
$league3 = League::getUnifiedRanking( 3, $previousSeason->id);
//$lastLeagues = League::where('season_id','=',$previousSeason->id)->get();
/*
foreach ($users as $index => $user) {
$found = false;
foreach ($usersLastSeason as $userLastSeason) {
if ($userLastSeason->id == $user->id) $found = true;
}
if (!$found) {
$users[$index]['rank']=League::RANK_LEAGUE3; // In der letzten Season unter den Actives nicht gefunden
$leagueMember = LeagueMember::create([
'user_id' => $user->id,
'league_id' => $league3->id
]);
$leagueMember->save();
} else {
// League1, 1-16: RANK_LEAGUE1
// League1, 17-22: RANK_LEAGUE2
// League2, 1-6: RANK_LEAGUE1
// League2, 7-16: RANK_LEAGUE2
// League2, 17-22: RANK_LEAGUE3
// League3, best6: RANK_LEAGUE2
// League3, 7-end: RANK_LEAGUE3
//
//alte Ligen durchsuchen und entsprechend einordnen
foreach($league1 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
$leagueId = -1;
if ($user->id == $userId) {
$rank=-1;
if ($index<16) {
$rank=1;
$leagueId=$league1->id;
} else {
$rank=2;
$leagueId=$league2->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
foreach($league2 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
$leagueId = -1;
if ($user->id == $userId) {
$rank=-1;
$leagueId=$league1->id;
if ($index<6) {
$rank=1;
} elseif ($index<16) {
$rank=2;
$leagueId=$league2->id;
} else {
$rank=3;
$leagueId=$league3->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
foreach($league3 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
if ($user->id == $userId) {
$rank=-1;
if ($index<6) {
$rank=2;
$leagueId=$league2->id;
} else {
$rank=3;
$leagueId=$league3->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
}
}
*/
}
}

View file

@ -1,36 +0,0 @@
<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\User;
class LeagueMember extends Model
{
protected $table ='leagues_members';
protected $fillable = [
'id','user_id','league_id'
];
//
public static function getMembers($league_id) {
$members =LeagueMember::where('league_id','=',$league_id)->orderBy('id')->get();
$userList=array();
foreach($members as $member) {
array_push($userList,$member->user_id);
}
return $userList;
}
public static function playsInRound($userId, $roundId, $leagueId) {
$matches1 = Match::where('user1_id','=',$userId)->where('round_id','=',$roundId)->where('league_id','=',$leagueId)->get();
if (sizeof($matches1)>0) return true;
$matches2 = Match::where('user2_id','=',$userId)->where('round_id','=',$roundId)->where('league_id','=',$leagueId)->get();
return sizeof($matches2)>0;
}
}

View file

@ -1,329 +0,0 @@
<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\Leagues\League;
use App\Leagues\LeagueMember;
use App\User;
use App\Round;
use App\Season;
use App\Tipp;
use Log;
use DB;
class Match extends Model
{
protected $table ='leagues_matches';
protected $fillable = [
'id','league_id','round_id','user1_id','user2_id'
];
// https://en.wikipedia.org/wiki/Round-robin_tournament
public static function createMatchups()
{ // should be restricted to league ranks 1,2,3 and 4. All other leagues will have to use some
// incremental matchmaking system.
Log::info("Match::Creating matchups()");
$currentSeason = Season::getCurrent();
$leagues = League::where('season_id', '=', $currentSeason->id)->get();
foreach ($leagues as $league) {
error_log("Match::createMatchups league_id=".$league->id);
Log::info("Match::createMatchups: Creating matchups for league_id=".$league->id);
// Wenn es keine previous League gibt, dann ist $league->rank immer RANK_QUALIFICATION,
// ansonsten ist es einer von RANK_LEAGUE1, RANK_LEAGUE2, RANK_LEAGUE3
Log::info("rank_id of league_id ".$league->id." = ".$league->rank);
if ($league->rank <= League::RANK_QUALIFICATION) {
$rounds = Round::where('id','>=',$league->start_round_id)->get();
error_log("Match::createMatchups. start_round_id = ".$league->start_round_id);
$roundNr=1;
$neededRoundCount = Match::getNumberOfNeededRounds($league->id);
Log::info("Match::createMatchups( league_id=".$league->id.", numberOfrounds=".sizeof($rounds));
$allPairings=Match::getAllPairings($league->id);
Log::info("Match::createMatchups: Rounds:");
$counter=1;
foreach($rounds as $round) {
Log::info($counter);
Log::info($round."\n");
$counter+=1;
}
Log::info("Match::createMatchups: League-id=".$league->id.", Size of allPairings:".sizeof($allPairings));
foreach ($rounds as $round) {
Log::info("Match::createMatchups: Fetching roundNr/index=".$roundNr);
$pairings = $allPairings[$roundNr];
// Save pairings
foreach($pairings as $pair) {
Log::info("Match::createMatchups: Saving match. " . $pair[0] . " vs " . $pair[1] . " roundid=" . $round->id);
$newMatch = Match::create([
'league_id' => $league->id,
'round_id' => $round->id,
'user1_id' => $pair[0],
'user2_id' => $pair[1]
]);
$newMatch->save();
//Log::info("Saving match: league_id=".$league->id.", round_id=".$round->id.", ".$pair[0]." vs ".$pair[2]);
}
$roundNr += 1;
if ($roundNr > $neededRoundCount) break;
}
} else {Log::info("Match::createMatchups: Skipped match creation because of unfitting rank=".$league->rank);}
}
}
public static function hasMatched($user1_id, $user2_id, $league_id)
{
$matches = DB::table('leagues_matches')
->where('league_id', '=', $league_id)
->where('user1_id', '=', $user1_id)
->where('user2_id', '=', $user2_id)
->get();
if (sizeof($matches)) {
return true;
}
$matches = DB::table('leagues_matches')
->where('league_id', '=', $league_id)
->where('user1_id', '=', $user2_id)
->where('user2_id', '=', $user1_id)
->get();
if (sizeof($matches)) {
return true;
}
return false;
}
// Selektiert nur die "Heimspiele"
public static function getMatches($user_id, $league_id) {
$matches = DB::table('leagues_matches')->where('league_id', '=', $league_id)->where('user1_id','=',$user_id)->get();
return $matches;
}
public static function getLeagueMatches($leagueId) {
//error_log("App\Match::getLeagueMatches(leagueId=".$leagueId.")");
$matches = DB::table('leagues_matches')->where('league_id','=',$leagueId)->orderBy('round_id')->get();
$league=League::where('id','=',$leagueId)->first();
$season = Season::where('id','=',$league->season_id)->first();
$roundnames = Round::getNames($season->id);
$usernames = User::getNames();
foreach($matches as $match) {
//error_log("Needed round_id: ".$match->round_id);
$match->round_name = $roundnames[$match->round_id];
$match->user1_name = $usernames[$match->user1_id];
$match->user2_name = $usernames[$match->user2_id];
// Punktauswertung in Match::getMatchResults($leagueId, $maxRoundId);
}
return $matches;
}
// Hier findet RoundRobin statt.
public static function getAllPairings($leagueId) {
Log::info("GetAllPairings for LeagueId=".$leagueId);
$members = LeagueMember::getMembers($leagueId);
$roundCount=Match::getNumberOfNeededRounds($leagueId);
if (sizeof($members) % 2 == 1) { // ungerade memberzahl => freilos einfügen
error_log("Adding -1 free entry");
Log::info("Adding -1 free entry");
array_push($members,-1);
}
shuffle($members);
error_log("Number of members:".sizeof($members));
Log::info("Number of members.".sizeof($members));
$pairingCount = Match::getNumberOfPairingsPerRound($leagueId);
error_log("pairingCount=".$pairingCount);
Log::info("pairingCount=".$pairingCount);
$all = array();
for ($currentRoundNr=1; $currentRoundNr<= $roundCount; $currentRoundNr++) {
$roundRobin = array();
foreach ($members as $userId) {
array_push($roundRobin, $userId);
}
//error_log("RoundNr ".$currentRoundNr." Array start:");
//error_log(implode(",",$roundRobin));
Log::info("RoundNr ".$currentRoundNr." Array start:");
Log::info(implode(",",$roundRobin));
$_roundNr = $currentRoundNr;
while ($_roundNr >= 1) {
// Round-Robin shift: First element stays, rest rotates
$first = array_shift($roundRobin); // Erstes Element sichern & entfernen
$last = array_pop($roundRobin); // Letztes Element sichern & entfernen
array_unshift($roundRobin, $last); // Vorne einfügen
array_unshift($roundRobin, $first); // Vorne einfügen
$_roundNr--;
}
//error_log("RoundNr ".$currentRoundNr." Array end:");
//error_log(implode(",",$roundRobin));
Log::info("RoundNr ".$currentRoundNr." Array end:");
Log::info(implode(",",$roundRobin));
$idx = 0;
$slot = 0;
$pairings = array();
foreach ($roundRobin as $index => $userId) {
$idx = $index;
if ($index >= $pairingCount) {
$idx = 2 * $pairingCount - $index - 1;
$slot = 1;
}
$pairings[$idx][$slot] = $userId;
//error_log($idx.",".$slot." => ".$userId);
Log::info($idx.",".$slot." => ".$userId);
}
// Matches die nur einen Teilnehmer haben entfernen. Passiert bei ungerader Teilnehmerzahl.
// Der nicht im Pairing befindliche Spieler hat einen spielfreien Tag.
//error_log(" Cleaning up Round pairings");
Log::info("Cleaning up Round pairings");
$pairings_clean=array();
//error_log(":".$pairings[0]);
foreach($pairings as $idx => $pairing) {
if ($pairing[0] == -1 || $pairing[1] == -1) {
//error_log("DONT ADD");
Log::info("DONT ADD");
} else {
//error_log("adding...");
Log::info("adding...");
$pairings_clean[$idx] = $pairing;
}
}
$all[$currentRoundNr]=$pairings_clean;
//$all[$currentRoundNr]=$pairings;
}
foreach ($all as $roundNr => $pairings) {
foreach ($pairings as $slotIdx => $pairing) {
error_log($pairing[0]." vs ".$pairing[1]);
Log::info($pairing[0]." vs ".$pairing[1]);
}
}
return $all; // $all[$roundnr]= Array of Tuples ( UserId1, UserId2 )
//return null;
}
public static function getNumberOfPairingsPerRound($leagueId) {
$members = LeagueMember::getMembers($leagueId);
$pairingsPerRound = intdiv(sizeof($members),2);
if (sizeof($members)-$pairingsPerRound*2) {
$pairingsPerRound+=1;
}
return $pairingsPerRound;
}
public static function getNumberOfNeededRounds($leagueId) {
$members = LeagueMember::getMembers($leagueId);
$memberCount = sizeof($members);
if ($memberCount % 2 == 1) { return $memberCount; } // 1 Runde mehr wg. Freilos für 1 Spieler
return $memberCount-1;
}
public static function getMatchResults($leagueId, $maxRoundId=-1) {
$league=League::where('id','=',$leagueId)->first();
$season=Season::where('id','=',$league->season_id)->first();
$roundtipps = Tipp::getRoundTipps($maxRoundId, $season->id);
$roundtipps = $roundtipps["roundtipps"];
$matches = Match::getLeagueMatches($leagueId, $maxRoundId);
if ($maxRoundId==-1) {
//$maxRoundId = Round::getLastRoundId($season->id);
$maxRoundId = Round::getLastLockedRoundId($season->id);
Log::info("LASTLOCKEDROUND_ID=".$maxRoundId);
}
foreach($matches as $key => $match) {
$user1_key = $match->round_id."_".$match->user1_id;
$user2_key = $match->round_id."_".$match->user2_id;
if (array_key_exists($user1_key,$roundtipps ) && array_key_exists($user2_key,$roundtipps) ) {
$user1_score = $roundtipps[$user1_key]["rankscore"];
$user2_score = $roundtipps[$user2_key]["rankscore"];
$matches[$key]->user1_rankscore = $user1_score;
$matches[$key]->user2_rankscore = $user2_score;
//$matches[$key]->user1_hits = $roundtipps[$user1_key][]
if ($user1_score > $user2_score) {
$matches[$key]->user1_league_score = 3;
$matches[$key]->user2_league_score = 0;
}
else if ($user1_score < $user2_score){
$matches[$key]->user1_league_score = 0;
$matches[$key]->user2_league_score = 3;
} else {
$matches[$key]->user1_league_score = 1;
$matches[$key]->user2_league_score = 1;
}
} else { // Untipped/future round
$matches[$key]->user1_league_score = 0;
$matches[$key]->user2_league_score = 0;
$matches[$key]->user1_rankscore = -1;
$matches[$key]->user2_rankscore = -1;
}
}
return $matches;
}
public static function getMatchResultsForUser($userId, $maxRoundId=-1) {
$season = Season::getCurrent();
$leagues = League::where('season_id','=',$season->id)->get();
$matchList=array();
foreach($leagues as $league) {
$member=LeagueMember::where('league_id','=',$league->id)->where('user_id','=',$userId)->first();
if ($member) {
// $userId ist member dieser League
$matchResults = Match::getMatchResults($league->id,$maxRoundId);
foreach($matchResults as $result) {
if ($result->user1_id == $userId || $result->user2_id==$userId) {
array_push($matchList, $result);
}
}
}
}
return $matchList;
}
}