Jump to content

PHP Tournament Bracket System


erdem

Recommended Posts

Hi Guys,

 

Happy new year to all!!

 

I'm trying to make starcraft 2 tournament web site for me and friends.

 

i stuck on tournament system.

 

I have a jquery script that makes a bracket but I couldn't figure out how can I implament it with my database and php:(

 

I would like to ask you some questions please.

 

I have this html and jquery script.

 

my mysql database is like this

 

tournamenttree

 

id - UserID - TournamentID - Round

 

1        - 1              - 1                -  1

2        - 15            - 1                -  1

3        - 17            -  1                - 1

4        - 25            - 1                  - 1

 

and

 

tournaments

 

id - tournamentname - createdtime - players - active

 

1        -Sunday Cup    -  time()          -      4  -    1

 

and Users table

 

<?php
    $link = mysql_connect( '', ', ' );
if ( !is_resource( $link ) ) die( 'MySQL Connect Error' );
if ( !mysql_select_db( 'db6968_game', $link ) ) die( 'MySQL DB Error' );
mysql_query( "SET CHARACTER SET UTF8" );
mysql_query( "SET collation_connection = 'utf8_turkish_ci'" );
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us">
<head>
  <title>MyTournamentName</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript'>
</script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js' type='text/javascript'>
</script>  
  <style type="text/css">
  .tournament {    
    background-color: #F0F0F0;
    border: dashed 1px solid;
    overflow: auto;
  }
  .tournament .bracket {
    background-color: #DFDFDF;
    min-width: 100px;    
    vertical-align: top;
    float: left;
  }
  
  .tournament .bracket .match {
    background-color: #D0D0D0;
    border-top: 1px solid;
    border-right: 1px solid;
    border-bottom: 1px solid;  
  }
  .tournament .bracket .match .p1 {    
    height: 20px;
  }
  .tournament .bracket .match .p2 {
    height: 20px;
  }    
  .tournament .bracket .match .spacer {
    background-color: #DFDFDF;
    height: 38px;
  }
  .tournament .bracket .spacer {
    height: 80px;
  }
  .tournament .bracket .half-spacer {
    height: 40px;
  }
  .tournament .bracket .small-spacer {
    height: 10px;
    background-color: #F1F1F1;
  }
  .tournament .bracket .winner {
    border-bottom: 1px solid;
  }
  
  .left-line {
    border-left: 1px solid;
  }
  
  .tournament .cell {
    min-width: 100px;
    height: 20px;
    float: left;
    background-color: #DFDFDF;    
  }   
  .tournament .l2 {
    background-color: #D0D0D0;
  }     
  .tournament .lmax {
    width: 0px;
    clear: both;
  }    
  </style>
  <script type="text/javascript">
    

    var matchInfo = {
      "rounds" : [
        { "name": "Round1", "matches" : [
            { "id" : 1, "p1" : "mTwDeMuslim", "p2" : "Luffy" },
            { "id" : 2, "p1" : "SeleCT", "p2" : "NEXGenius" },
            { "id" : 3, "p1" : "Fenix", "p2" : "SoftBall" },
            { "id" : 4, "p1" : "White-Ra", "p2" : "Ice" },
            { "id" : 5, "p1" : "HuK", "p2" : "RedArchon" },
            { "id" : 6, "p1" : "Capoch", "p2" : "Loner" },
            { "id" : 7, "p1" : "mTwDIMAGA", "p2" : "MakaPrime" },
            { "id" : 8, "p1" : "TLAF-Liquid`TLO", "p2" : "SEN" }
          ]
        },
        { "name": "Round2",
          "matches" : [
            { "id" : 9, "p1" : null, "p2" : null },
            { "id" : 10, "p1" : null, "p2" : null },
            { "id" : 11, "p1" : null, "p2" : null },
            { "id" : 12, "p1" : null, "p2" : null }
          ]
        },
        { "name": "Round3",
          "matches" : [
            { "id" : 13, "p1" : null, "p2" : null },
            { "id" : 14, "p1" : null, "p2" : null },
          ]
        },
        { "name": "Round4",
          "matches" : [
            { "id" : 15, "p1" : null, "p2" : null },
          ]
        } 
      ]
    };
  
    $(document).ready(function($) {       
      var base = $('#writeHere');
      var matchDivsByRound = [];
      
      for (var roundIndex=0; roundIndex<matchInfo.rounds.length; roundIndex++) {    
        var round = matchInfo.rounds[roundIndex];
        var bracket = checkedAppend('<div class="bracket"></div>', base);
        var matchDivs = [];
        matchDivsByRound.push(matchDivs);
        
        //setup the match boxes round by round
        for (var i=0; i<round.matches.length; i++) {                     
          var vOffset = checkedAppend('<div></div>', bracket);
        
          var match = round.matches[i];
          var matchHtml = '<div class="match" id="match' + match.id + '">'
            + '<div class="p1">' + fmtName(match.p1) + '</div>'
            + '<div class="spacer"></div>'
            + '<div class="p2">' + fmtName(match.p2) + '</div>';
          matchDiv = checkedAppend(matchHtml, bracket);
          matchDivs.push(matchDiv);
          
          if (roundIndex > 0) {
            //row 2+; line up with previous row
            var alignTo = matchDivsByRound[roundIndex-1][i*2];
            //offset to line up tops
            var desiredOffset = alignTo.position().top - matchDiv.position().top;
            
            //offset by half the previous match-height
            desiredOffset += alignTo.height() / 2;
            vOffset.height(desiredOffset);            
          } else {
            checkedAppend('<div class="small-spacer"></div>', bracket);
          }
          
          if (roundIndex > 0) {
            //tweak our size so we stretch to the middle of the appropriate element
            var stretchTo = matchDivsByRound[roundIndex-1][i*2+1];
            var newH = stretchTo.position().top + stretchTo.height()/2 - matchDiv.position().top;            
            var deltaH = newH - matchDiv.height();
            matchDiv.height(newH);
            var spacer = matchDiv.find('.spacer');
            spacer.height(spacer.height() + deltaH);
          }          
        }                
      }
      //setup the final winners box; just a space for a name whose bottom is centrally aligned with the last match
      bracket = checkedAppend('<div class="bracket"></div>', base);
      var vOffset = checkedAppend('<div></div>', bracket);
      var alignTo = matchDivsByRound[matchInfo.rounds.length - 1][0]; //only 1 match in the last round
      var html = '<div class="winner">?</div>';
      var winnerDiv = checkedAppend(html, bracket);      
      vOffset.height(alignTo.position().top - winnerDiv.position().top + alignTo.height() / 2 - winnerDiv.height());
    });
    
    function fmtName(name) {
      return null != name ? name : '?';
    }
    
    function checkedAppend(rawHtml, appendTo) {
      var html = $(rawHtml);
      if (0 == html.length) {
        throw "Built ourselves bad html : " + rawHtml;
      }
      html.appendTo(appendTo);      
      return html;
    }
  </script>
</head>
<body>
  <div>blah blah blah</div>
  <div id="writeHere" class="tournament"></div>
  <div>blah blah blah</div>
</body>
</html>

 

 

I tried to do this

 

<?php
function getusername($id){
             $sql = mysql_query("SELECT * FROM users WHERE UserID = '".$id."'");
             $ROW = mysql_fetch_assoc($sql);
                 $data = $ROW['Username'];
             
             return $data;
         }
         ?>
         
             var matchInfo = {
             "rounds" : [
        { "name": "Round1", "matches" : [
        <?php
        
        
        for ($i = 0; $i < $num_rounds; ++$i)
   {
    $matches = $teams * pow(.5, $i - 1) / 2;
    $ROW = mysql_fetch_array($sql);
    for ($j = 0; $j < $matches; ++$j)
    {
        
        echo '{ "id" : '.$j.', "p1" : "'.$ROW['UserID'].'", "p2" : "'.$ROW['UserID' + $j - 1].'" }';
        echo $coma = ',';
      }
      echo $coma= '';
   }?>


 

 

but it gives me this

 

 var matchInfo = {
             "rounds" : [
        { "name": "Round1", "matches" : [
        { "id" : 0, "p1" : "1", "p2" : "" },{ "id" : 1, "p1" : "1", "p2" : "2" },{ "id" : 2, "p1" : "1", "p2" : "1" },{ "id" : 3, "p1" : "1", "p2" : "1" },{ "id" : 0, "p1" : "15", "p2" : "" },{ "id" : 1, "p1" : "15", "p2" : "3" },{ "id" : 0, "p1" : "17", "p2" : "" }, 
          ]
        },

 

according to my database there are 4 teams but with my php script it gives me 7 matches. it should be only 2 matches. cos there are 4 teams.

 

i just cannot figure out this. is there anyone can give me an idea or help me please? thanks

Link to comment
https://forums.phpfreaks.com/topic/254074-php-tournament-bracket-system/
Share on other sites

I would get rid of the javascript, and stick with a pure php solution. when you have your php solution working than add your javascript.

 

I wrote this routine a number of years ago

<?php
    $teams=array('Alpha','Beta','Gamma','Delta','Epsilon','Zeta','Eta');
    
    define('MY_EOL','<br .>'.PHP_EOL);

    $round=0;
    
    $participants=$teams;
    while(count($participants)>1)
    {
        $round++;  // Increment our round
        Echo 'Round '. $round. MY_EOL;
        $tables=array();  // Clear our tables
        $index=0;
        while(count($tables) < floor(count($participants)/2))  // want an even amount of tables
            $tables[]=array($participants[$index++],$participants[$index++]);
        if($index<count($participants))// extra team, add to tables, but no opposing team
            $tables[]=array($participants[$index++],NULL); 
        $participants=array(); // clear out next round participants
        foreach($tables as $idx=>$table)
        {
            $tbl=$idx+1;
            echo " Table #{$tbl}: ";
            if($table[1]===NULL)  // extra team advances to next level automatically
            {
                echo "{$table[0]} Holdover";
                $winner=0;
            } else  {
                echo "{$table[0]} vs. {$table[1]}";
                $winner=rand(0,1);    // Generate a winner
            }
            echo " - Winner {$table[$winner]}". MY_EOL;
            $participants[]=$table[$winner];  // Add WInnerto next round
        }
    }  
?>

 

 

hi laffin,

 

Thanks for your help. It helped a lot!!

 

It works.

 

I just want to ask you something.

 

I didn't change your code and I add my mysql codes.

 

How can I change winner. It should come from database. Shouldn't it? How can I change it using a database record?

 

Is there anything you could you say to this. If any suggestion from you. it would be helpful also. Thanks again and happy new year.

 

£

<?php

sql = mysql_query("SELECT * FROM tournamenttree WHERE Tournamet = '1'");

$teams = array();
while($ROW = mysql_fetch_assoc($sql)){
     $data[]=get_username($ROW['UserID']).',';
        
}

$teams = ($data); 
    



    
    
    define('MY_EOL','<br .>'.PHP_EOL);

    $round=0;
    
    $participants=$teams;
    while(count($participants)>1)
    {
        $round++;  // Increment our round
        Echo 'Round '. $round. MY_EOL;
        $tables=array();  // Clear our tables
        $index=0;
        while(count($tables) < floor(count($participants)/2))  // want an even amount of tables
            $tables[]=array($participants[$index++],$participants[$index++]);
        if($index<count($participants))// extra team, add to tables, but no opposing team
            $tables[]=array($participants[$index++],NULL); 
        $participants=array(); // clear out next round participants
        foreach($tables as $idx=>$table)
        {
            $tbl=$idx+1;
            echo " Table #{$tbl}: ";
            if($table[1]===NULL)  // extra team advances to next level automatically
            {
                echo "{$table[0]} Holdover";
                $winner=0;
            } else  {
                echo "{$table[0]} vs. {$table[1]}";
                $winner=rand(0,1);    // Generate a winner
            }
            echo " - Winner {$table[$winner]}". MY_EOL;
            $participants[]=$table[$winner];  // Add WInnerto next round
        }
    }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.