Generate random chess position: Difference between revisions

Added Crystal translation of Ruby version.
m (→‎{{header|Perl}}: simplify list 'quoting')
(Added Crystal translation of Ruby version.)
Line 215:
P.r.rP.P
P..q...n
</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<lang ruby>def hasNK(board, a, b)
(-1..1).each do |g|
(-1..1).each do |f|
aa = a + f; bb = b + g
if (0..7).includes?(aa) && (0..7).includes?(bb)
p = board[aa + 8 * bb]
return true if p == "K" || p == "k"
end
end
end
return false
end
 
def generateBoard(board, pieces)
while pieces.size > 1
p = pieces[pieces.size - 1]
pieces = pieces[0...-1]
while true
a = rand(8); b = rand(8)
next if ( (b == 0 || b == 7) && (p == "P" || p == "p") ) ||
( (p == "k" || p == "K") && hasNK(board, a, b) )
break if board[a + b * 8] == '.'
end
board[a + b * 8] = p
end
end
 
pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN"
11.times do
e = pieces.size - 1
while e > 0
p = rand(e); t = pieces[e]
#pieces[e] = pieces[p]; pieces[p] = t; e -= 1 # in Ruby
pieces = pieces.sub(e, pieces[p]); # in Crystal because
pieces = pieces.sub(p, t); e -= 1 # strings immutable
end
end
 
# No 'nil' for Crystal arrays; use '.' for blank value
board = Array.new(64, '.'); generateBoard(board, pieces)
puts
e = 0
8.times do |j|
8.times do |i|
if board[i + 8 * j] == '.'; e += 1
else
(print(e); e = 0) if e > 0
print board[i + 8 * j]
end
end
(print(e); e = 0) if e > 0
print("/") if j < 7
end
 
print(" w - - 0 1\n")
8.times do |j|
8.times { |i| board[i + j * 8] == '.' ? print(".") : print(board[i + j * 8]) }
puts
end
 
# Simpler for same output
8.times{ |row| puts board[row*8..row*8 + 7].join("") }
</lang>
{{out}}<pre>
1n1P3p/1p1k2Pp/1ppPPprn/2rP4/KNRQ2b1/2Bp1PP1/3qPBN1/2Rp4 w - - 0 1
.n.P...p
.p.k..Pp
.ppPPprn
..rP....
KNRQ..b.
..Bp.PP.
...qPBN.
..Rp....
 
</pre>
 
Anonymous user