User Tools

Site Tools


web_development:random_ballot_draw

We needed a way to be able to conduct random draws on Category5.TV, but wanted to do more than just randomly pick a name; we wanted something visual.

So, I whipped out this script, which uses Javascript refreshes and PHP to drive a draw with visual output.

Of course, the display itself can be easily tweaked, as it's really just outputting HTML and then refreshing the page after a specified timeout (it starts out fast, and slows down as it gets closer to the winner).

By chaning the ballot qty value, a single person can have more than one ballot. This is used when we offer an option to “increase your chances of winning”, such as the 2009 Christmas Giveaway.

random_ballot_draw.php
<?php
  $v = 0;
 
  $ballot[$v][name] = "Robbie";
  $ballot[$v][qty] = 1;
  $v++;
 
  $ballot[$v][name] = "Popey";
  $ballot[$v][qty] = 2;
  $v++;
 
  $inflate = 1; // inflate the names list, comment out to disable - can be a fun way to infuse comical names into the display
  $inflatenames = array('Bruce', 'Doug');
 
  // cast all ballots
  $w = 0;
  foreach ($ballot as $key => $value) {
    $q = 0;
    while ($q < $value[qty]) {
      $ballot2[$w] = $value[name];
      $q++;
      $w++;
    }
  }
  unset($ballot);
  $ballot = $ballot2;
  unset($ballot2);
 
  $count = $_GET['count'];
  if ($count < 198) {
    if ($inflate && $count < 196 && rand(0,3) == 2) { $name = $inflatenames[rand(0,(sizeof($inflatenames)-1))]; } else { $name = $ballot[rand(0,(sizeof($ballot)-1))]; }
  } else { $name = $_GET['name']; }
  $count++;
 
  $size = floor($count/2);
?>
 
<html>
<body bgcolor="#333333">
<table border="0" width="100%" height="100%"><td valign="middle" align="center" style="font-family: Verdana; font-size: <?= $size ?>px; color: #fff;">
<?php
$timeout = 2000;
if ($count < 198) $timeout = 1000;
if ($count < 195) $timeout = 600;
if ($count < 190) $timeout = 500;
if ($count < 180) $timeout = 400;
if ($count < 170) $timeout = 300;
if ($count < 160) $timeout = 200;
if ($count < 150) $timeout = 100;
if ($count < 100) $timeout = 10;
 
if ($count <= 199) { ?>
<script type="text/javascript"><!--
setTimeout('Redirect()',<?= $timeout; ?>);
function Redirect()
{
  location.href = '?count=<?= $count ?>&name=<?= $name ?>';
}
// --></script>
<?php
echo $name;
}
else
{
echo '<small>WINNER:</small><br /><strong>' . $name . '</strong>';
}
?>
</td></table>
</body>
</html>
web_development/random_ballot_draw.txt · Last modified: 2012/01/26 09:02 by import