I am about to create a script that choose a winner for my lottery. The amount of tickets is chosen by following: amount of money * 100
So $1.26 = 126 tickets.
I made this, which give me the winning ticket number, but then I cannot get the winning user:
$totaltickets = 0;
foreach($players as $player){
$totaltickets += $player->depositedValue*100;
}
$winningTicket = rand(1,$totaltickets);
I have rows like this:
Player1 - 1.25$
Player2 - 5.99$
etc..
If it is possible then I would like to keep it like this, and not have 1000s of rows in the database with each ticket.
You can use this code:
<?php
function getWinnerPlayer($players) {
/* get total amount of tickets */
$total_tickets = 0;
foreach ($players as $player) {
/* var_dump($player->depositedValue); */
$total_tickets += $player->depositedValue * 100;
}
/* get winner ticket */
$winner = rand(1, $total_tickets);
/* return winner player */
$count = 0;
foreach ($players as $player) {
// $total_tickets is not the correct variable, sorry
// $count += $total_tickets->depositedValue * 100;
$count += $player->depositedValue * 100;
if ($count >= $winner) return $player;
}
}
?>
I'm thinking of keeping your idea of numbers instead of bring in an array.
I'm going to have the players hold their ticket positions (start/end). When I pick a random ticket, I'm going to see if my number is within their bounds, and if it is, then I have found the winner.
<?php
class TicketMaster {
private $players = array();
public $total = 0;
public function addPlayer($player) {
$player->tickets[0] = $this->total;
$this->total += $player->value;
$player->tickets[1] = $this->total;
$this->players[] = $player;
}
public function selectWinner() {
$ticket = rand(0, $this->total);
foreach ($this->players as $player)
if ($ticket >= $player->tickets[0] && $ticket <= $player->tickets[1])
return $player;
return false;
}
}
class Player {
public $name = '';
public $value = 0;
public $tickets = array(0, 0);
function __construct($name, $value) {
$this->name = $name;
$this->value = $value;
}
}
$ticketMaster = new TicketMaster();
$ticketMaster->addPlayer(new Player("John", 200));
$ticketMaster->addPlayer(new Player("Mike", 200));
$ticketMaster->addPlayer(new Player("Dave", 1000));
echo $ticketMaster->selectWinner()->name;
Also
$ticket = rand(0, $this->total); //change to random_int, but I kept it at rand because eval.in only works with this one
Output: Dave
Dave wins most of the time because he has like 1000 tickets, over the other two players who only have 400 combined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With