A PHP Fischer Random Chess Function

This is of limited use, but I thought I’d share the source code to a function I wrote the other day to setup a game of Fischer Random Chess, also known as Chess 960.

The basic idea of Fischer Random Chess is that you shuffle up the back row. The rules say that; 1) the bishops must be on opposite colored squares, 2) that the rooks be on opposite sides of the king, and 3) that the black and white side must mirror each other. That’s it. The game is played out like a standard game of chess, though castling is a little tricky.

The function below outputs an array where the keys are correspond to squares on the board. The array values specify what pieces occupy each square. For example:


means that a light (white) rook is at square c1. The pieces are noted with the standard letters (r,n,b,q,k). In theory it wouldn’t be hard at all to get it to output in FEN either, though (at the moment) I’m not interested in that personally.

I’ll be incorparating this into Some Chess, but it could be used in any program or used to setup a real world game too, you just need to work with the array. Check back soon and I’ll share the code used by Some Chess to display an array like the one outputted below as a graphical chessboard.

function fisher_random(){
// create an array of every possible square
$squares = array(0=>’a’,1=>’b’,2=>’c’,3=>’d’,4=>’e’,5=>’f’,6=>’g’,7=>’h’);

// the get the bishop first
$tmp = array_rand(array(0=>’a’,2=>’c’,4=>’e’,6=>’g’)); // bishops must be on opposite colors, so only offer one color to each bishop
$bishop1 = $squares[$tmp];
unset($squares[$tmp]); // remove the square the bishop got from the array of possible squares

// get the second bishop
$tmp = array_rand(array(1=>’b’,3=>’d’,5=>’f’,7=>’h’));
$bishop2 = $squares[$tmp];

// place the queen
$tmp = array_rand($squares); // just use php’s array_rand() function to pick from the array of possible squares
$queen = $squares[$tmp];

// place one knight
$tmp = array_rand($squares);
$knight1 = $squares[$tmp];

// place now place the other knight
$tmp = array_rand($squares);
$knight2 = $squares[$tmp];

// take what is left and place the rook, king, and other rook— in that order
foreach($squares as $tmp){
if($i==0) $rook1 = $tmp;
if($i==1) $king = $tmp;
if($i==2) $rook2 = $tmp;

// return an array of the pieces, the array keys correspond to the squares and their values to pieces occupying those squares
return array(