Skip to content

Instantly share code, notes, and snippets.

@sroller
Created April 18, 2022 22:41
Show Gist options
  • Save sroller/c6876c16b136e20c036a20e262b06bff to your computer and use it in GitHub Desktop.
Save sroller/c6876c16b136e20c036a20e262b06bff to your computer and use it in GitHub Desktop.
create Chess960 starting positions
#!/usr/bin/env ruby
# create Chess960 starting position
# algorithm from https://en.wikipedia.org/wiki/Fischer_random_chess_numbering_scheme
knight_positions = [
['N', 'N', '.', '.', '.'],
['N', '.', 'N', '.', '.'],
['N', '.', '.', 'N', '.'],
['N', '.', '.', '.', 'N'],
['.', 'N', 'N', '.', '.'],
['.', 'N', '.', 'N', '.'],
['.', 'N', '.', '.', 'N'],
['.', '.', 'N', 'N', '.'],
['.', '.', 'N', '.', 'N'],
['.', '.', '.', 'N', 'N']
]
# place knight on free square according to
# position table
def place_knights(row, knight_positions, n)
i = 0
knights = knight_positions[n]
row.each_with_index do |square, index|
next unless square == '.'
row[index] = 'N' if knights[i] == 'N'
i += 1
end
row
end
# place queen on Nth free column
def place_queen(row, n)
i = 0
row.each_with_index do |square, index|
next unless square == '.'
if i == n
row[index] = 'Q'
break
end
i += 1
end
row
end
def place_king_and_rooks(row)
i = 0
row.each_with_index do |square, index|
next unless square == '.'
case i
when 0
row[index] = 'R'
when 1
row[index] = 'K'
when 2
row[index] = 'R'
end
i = i + 1
end
row
end
# starting position in FEN
def fen(row)
"#{row.join.downcase}/pppppppp/8/8/8/8/PPPPPPPP/#{row.join} w KQkq - 0 1"
end
row = Array.new(8) { '.' }
N1 = rand(960)
# N1 = 518 # standard chess
N2, B1 = N1.divmod(4)
# light squared bishop
row[B1 * 2 + 1] = 'B'
N3, B2 = N2.divmod(4)
# dark squared bishop
row[B2 * 2] = 'B'
N4, Q = N3.divmod(6)
place_queen(row, Q)
place_knights(row, knight_positions, N4)
place_king_and_rooks(row)
puts "Chess960 starting position #{N1}"
puts fen(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment