Randomizing a game board
Posted: Fri Jun 02, 2006 12:21 am
I'm writing a game that has 25 positions on a game board. Each position will contain a different game piece (represented as integers from 0-25). This is a game where you try to find 4 preselected pieces on the board. I've chosen piece 0,1,2,3 as the pieces that must be found. They win if they find those pieces in 4 guesses.
What I need to do is randomize the pieces each time the game is played. Winners of the game will win actual prizes so I have to make each game play as randomized as possible to limit the number of payouts.
I've written the following game board randomizer but I'm not sure if this the most random way to do this.
Any input would be greatly appreciated.
Eric
What I need to do is randomize the pieces each time the game is played. Winners of the game will win actual prizes so I have to make each game play as randomized as possible to limit the number of payouts.
I've written the following game board randomizer but I'm not sure if this the most random way to do this.
Code: Select all
class GameEngine {
function GameEngine() {
}
function generateGameMatrix() {
$beginningArray[0] = 0;
$beginningArray[1] = 1;
$beginningArray[2] = 2;
$beginningArray[3] = 3;
$beginningArray[4] = 4;
$beginningArray[5] = 5;
$beginningArray[6] = 6;
$beginningArray[7] = 7;
$beginningArray[8] = 8;
$beginningArray[9] = 9;
$beginningArray[10] = 10;
$beginningArray[11] = 11;
$beginningArray[12] = 12;
$beginningArray[13] = 13;
$beginningArray[14] = 14;
$beginningArray[15] = 15;
$beginningArray[16] = 16;
$beginningArray[17] = 17;
$beginningArray[18] = 18;
$beginningArray[19] = 19;
$beginningArray[20] = 20;
$beginningArray[21] = 21;
$beginningArray[22] = 22;
$beginningArray[23] = 23;
$beginningArray[24] = 24;
$finalArray = array();
while(sizeof($beginningArray) > 0) {
$tempIndex = $this->selectRandomIndexFromArray($beginningArray);
$finalArray[] = $beginningArray[$tempIndex];
$beginningArray = $this->rebuildArrayWithoutIndex($beginningArray, $tempIndex);
}
return implode('|', $finalArray);
}
function selectRandomIndexFromArray($anArray) {
$upperLimit = sizeof($anArray) - 1;
return rand(0, $upperLimit);
}
function rebuildArrayWithoutIndex($beginningArray, $indexToRemove) {
$newArray = array();
foreach($beginningArray as $key => $value) {
if ($key != $indexToRemove) {
$newArray[] = $value;
}
}
return $newArray;
}
}Eric