Generate Chess960 starting position

From Rosetta Code
Generate Chess960 starting position is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Chess960 is a variant of chess created by world champion Bobby Fisher. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:

  • as in the standard chess game, all height pawns must be placed on the second rank.
  • pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
    • the bishops must be placed on opposite color squares ;
    • the King must be between two rooks ;

With those constraints there are 960 possible starting positions, thus the name of the variant.

The purpose of this task is to write a program that randomly generates a Chess960 initial position. You will show the result as the first rank displayed with Chess symbols in Unicode or with the letters King Queen Rook Bishop kNight.

Perl 6

<lang perl6>my Set $squares = set ^8;

$squares = $squares (-) set my @knights = $squares.pick(2); $squares = $squares (-) set my @bishops = $squares.list.grep(* % 2).pick, $squares.list.grep(* %% 2).pick; $squares = $squares (-) set my $queen = $squares.pick; my ($king, @rooks) = $squares.list[1, 0, 2];

my @squares;

@squares[$king, $queen, @rooks, @bishops, @knights] =

< K Q R R B B N N >;

say @squares;</lang>

Output:
Q N B R K B R N

Python

This uses indexing rather than regexps. Rooks and bishops are in upper and lower case to start with so they can be individually indexed to apply the constraints. This would lead to some duplication of start positions if not for the use of a set comprehension to uniquify the, (upper-cased), start positions.

<lang python>Python 3.4.0b1 (v3.4.0b1:3405dc9a6afa, Nov 24 2013, 19:09:12) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = sorted({.join(p).upper() for p in permutations(pieces)

                    if p.index('B') % 2 != p.index('b') % 2 		# Bishop constraint
                    and ( p.index('r') < p.index('K') < p.index('R')	# King constraint	
                          or p.index('R') < p.index('K') < p.index('r') ) })

>>> starts[0] 'BBNNQRKR' >>> starts[-1] 'RQNNKRBB' >>> len(starts) 960 >>> </lang>