我前段时间做过类似的事情,但是使用 sql 表来保存数据。也许这段代码会对你有所帮助:
$participants = 32;
$games = participantsToGames($participants);
$rounds = log($participants, 2);
echo "#Participants: $participants; games: $games; rounds: $rounds <br />";
echo "TRUNCATE TABLE `participants`;<br />";
for($i = 1; $i <= $participants; $i++){
echo "INSERT INTO `participants` (`title`) VALUES ('Driver $i');<br />";
}
echo "TRUNCATE TABLE `games`;<br />";
$participantsLeft = $participants;
$gameNumber = 1;
$gamesAfterLastRound = 1;
for($round = 1; $round <= $rounds; $round++){
$nrOfGames = $participantsLeft / 2;
for($gameNrThisRound = 1; $gameNrThisRound <= $nrOfGames; $gameNrThisRound++, $gameNumber++){
$nextGame = ($participantsLeft == 2)
? 0
: $gamesAfterLastRound -1 + ceil($nrOfGames + $gameNrThisRound / 2);
$nextGamePosition = ($gamesAfterLastRound -1 + ($nrOfGames + $gameNrThisRound / 2) == $nextGame)
? 'b'
: 'a';
if ($round == 1){
$a = ($participantsLeft * $gameNrThisRound / $nrOfGames) - 1;
$b = $a + 1;
echo $sql = "INSERT INTO `games` (`participant_a`, `participant_b`, `round`, `game_number`, `next_game`, `next_game_position`) "
."VALUES ('$a', '$b', '$round', '$gameNumber', '$nextGame', '$nextGamePosition');<br />";
}elseif ($round == $rounds){
echo $sql = "INSERT INTO `games` (`round`, `game_number`, `next_game`, `next_game_position`) "
."VALUES ('$round', '$gameNumber', '0', '0');<br />";
$gameNumber++;
echo $sql = "INSERT INTO `games` (`round`, `game_number`, `next_game`, `next_game_position`) "
."VALUES ('$round', '$gameNumber', '0', '0');<br />";
}else{
echo $sql = "INSERT INTO `games` (`round`, `game_number`, `next_game`, `next_game_position`) "
."VALUES ('$round', '$gameNumber', '$nextGame', '$nextGamePosition');<br />";
}
}
echo '#<br />';
$gamesAfterLastRound = $gameNumber;
$participantsLeft /= 2;
}
echo "UPDATE `games` SET `next_game` = 32 WHERE `next_game`=31";
function participantsToGames($participants){
if ($participants == 2) return 1;
return participantsToGames($participants / 2) + ($participants / 2);
}
/*
*
CREATE TABLE IF NOT EXISTS `games` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`participant_a` int(10) unsigned NOT NULL,
`participant_b` int(10) unsigned NOT NULL,
`winner` int(10) unsigned NOT NULL,
`round` smallint(5) unsigned NOT NULL,
`game_number` int(10) unsigned NOT NULL,
`next_game` int(10) unsigned NOT NULL,
`next_game_position` enum('a','b') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `participants` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`title` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
*/
只需将这两个表添加到数据库中,然后执行此脚本返回的 SQL 查询。您将有一张桌子供参与者使用,另一张桌子供游戏插槽使用。