Generate random chess position: Difference between revisions

→‎ZX Spectrum Basic: transposed board labels
(→‎ZX Spectrum Basic: transposed board labels)
(6 intermediate revisions by 3 users not shown)
Line 21:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V board = [[‘ ’] * 8] * 8
V piece_list = [‘R’, ‘N’, ‘B’, ‘Q’, ‘P’]
 
Line 79:
print(fen_from_board(board))
L(x) board
print(‘[’x.map(c -> ‘'’c‘'’).join(‘, ’)‘]’)</langsyntaxhighlight>
 
{{out}}
Line 96:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE BOARDSIZE="64"
DEFINE EMPTY="'."
 
Line 215:
Test("PPPPPPPPBBNNQRRppppppppbbnnqrr")
Test("PPBNQRppbnqr")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generate_random_chess_position.png Screenshot from Atari 8-bit computer]
Line 242:
=={{header|C}}==
{{trans|Java}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <math.h>
#include <string.h>
Line 325:
createFen();
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 343:
=={{header|C++}}==
 
<langsyntaxhighlight lang="cpp">
#include <ctime>
#include <iostream>
Line 419:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 446:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def hasNK(board, a, b)
(-1..1).each do |g|
(-1..1).each do |f|
Line 503:
 
# Simpler for same output
8.times{ |row| puts board[row*8..row*8 + 7].join("") }</langsyntaxhighlight>
{{out}}<pre>1n1P3p/1p1k2Pp/1ppPPprn/2rP4/KNRQ2b1/2Bp1PP1/3qPBN1/2Rp4 w - - 0 1
.n.P...p
Line 516:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit grouping io kernel math
math.parser math.ranges math.vectors prettyprint random
sequences sets splitting.monotonic strings ;
Line 570:
position [ position. ] [ position>fen print ] bi ;
 
MAIN: random-chess-position-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 586:
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<langsyntaxhighlight lang="freebasic">
Dim Shared As Byte grid(8, 8), r, c
 
Line 658:
toFen()
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 676:
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">begin globals
short grid(8, 8) // 1-8
end globals
Line 792:
fn CreateFen
 
HandleEvents</langsyntaxhighlight>
{{output}}
<pre style="font-size: 32px">
Line 810:
=={{header|Go}}==
{{trans|Java}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 902:
rand.Seed(time.Now().UnixNano())
fmt.Println(createFen())
}</langsyntaxhighlight>
 
{{out}}
Line 919:
=={{header|Haskell}}==
Module RandomChess
<langsyntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase, TupleSections #-}
 
module RandomChess
Line 1,139:
 
getBoard :: State BoardState ChessBoard
getBoard = gets (sortBy boardSort . board)</langsyntaxhighlight>
 
Module Main
<langsyntaxhighlight lang="haskell">module Main where
 
import Control.Monad.State (evalState)
Line 1,170:
main = BoardState emptyBoard <$> newStdGen >>= draw . evalState buildBoard
where
buildBoard = placeKings >> placePawns >> placeRemaining >> getBoard</langsyntaxhighlight>
{{out}}
Run 1
Line 1,222:
Implementation:
 
<langsyntaxhighlight Jlang="j">getlayout=:3 :0
whilst. NB. first two positions are non-adjacent kings
(0{pos) e. (1{pos)+(,-)1 7 8 9
Line 1,254:
)
 
randfen=:b2fen@randboard</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> randfen''
q6J/1pb1p1p1/1Jq2k2/4p1Pp/1pP5/1K2Bp2/5p2/1P4P1 w - - 0 1
randfen''
Line 1,270:
randfen''
b1Q1Bb1J/j1N1PpK1/PpB1P1Pp/2pp2PN/3nnk2/3J4/P6P/1N2Qb1J w - - 0 1
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import static java.lang.Math.abs;
import java.util.Random;
 
Line 1,349:
return fen.append(" w - - 0 1").toString();
}
}</langsyntaxhighlight>
<pre>(lol, the black king is in check, it couldn't possibly be white's turn)
. . . . . B . .
Line 1,362:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
Array.prototype.shuffle = function() {
for (let i = this.length - 1; i > 0; i--) {
Line 1,441:
// example
console.log(randomFEN());
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,460:
 
'''Module''':
<langsyntaxhighlight lang="julia">module Chess
 
using Printf
Line 1,514:
printgrid(grid) = println(join((join(grid[r, :], ' ') for r in 1:size(grid, 1)), '\n'))
 
end # module Chess</langsyntaxhighlight>
 
'''Main''':
<langsyntaxhighlight lang="julia">grid = fill(' ', 8, 8)
Chess.randposition!(grid)
Chess.printgrid(grid)</langsyntaxhighlight>
 
{{out}}
Line 1,533:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.util.Random
Line 1,611:
fun main(args: Array<String>) {
println(createFen())
}</langsyntaxhighlight>
 
Sample output:
Line 1,627:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">g = ConstantArray["", {8, 8}];
While[Norm@First@Differences[r = RandomChoice[Tuples[Range[8], 2], 2]] <= Sqrt[2], Null];
g = ReplacePart[g, {r[[1]] -> "K", r[[2]] -> "k"}];
Line 1,643:
g = StringRiffle[Reverse[g], "/"];
g = g <> " w - - 0 1";
g</langsyntaxhighlight>
{{out}}
<pre>2N5/1P3P2/p1P3P1/5q2/8/5k1K/1p3p2/8 w - - 0 1</pre>
Line 1,649:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import random
 
type
Line 1,753:
 
randomize()
echo createFen()</langsyntaxhighlight>
 
{{out}}
Line 1,767:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,821:
}
 
say gen_FEN();</langsyntaxhighlight>
{{out}}
<pre>p5Nq/1nn5/3N2bp/PRBkQr2/1QB1Pn2/Q5pK/1NRb2rN/p1R2r1N w - - 0 1</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">show_bad_boards</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
Line 1,901:
<span style="color: #000000;">show_board</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">fen</span><span style="color: #0000FF;">()})</span>
<!--</langsyntaxhighlight>-->
To allow pawns that have "moved backwards", replace the inner test with
<code>if not find('P',board[1..8]) and not find('p',board[57..64]) then exit end if</code><br>
Line 1,943:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
(seed (in "/dev/urandom" (rd 8)))
(de pieceN (P)
Line 2,026:
(gt0 C)
(link C) ) ) ) ) ) ) )
(println (pack (glue "/" *FEN) " w - - 0 1"))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,041:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
import random
 
Line 2,107:
#entry point
start()
</syntaxhighlight>
</lang>
{{out}}<pre>
1p5k/1B4P1/1KN4R/nR3Nrb/Q1NrnpP1/7R/3PP3/1P5P w - - 0 1
Line 2,122:
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">
place_kings <- function(brd){
###
Line 2,220:
 
generate_fen()
</syntaxhighlight>
</lang>
{{out}}
Line 2,237:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub pick-FEN {
# First we chose how many pieces to place
my $n = (2..32).pick;
Line 2,270:
}
 
say pick-FEN();</langsyntaxhighlight>
{{out}}
<pre>q2n1n2/1Qpk3Q/1r3bP1/1b1b4/2pRBR2/4P1bN/2R3K1/N1r2rPB w - - 0 1</pre>
Line 2,282:
 
This version also allows any number of chessboards to be displayed &nbsp; (the default is to only display one chessboard).
<langsyntaxhighlight lang="rexx">/*REXX program generates a chess position (random pieces & positions) in a FEN format.*/
parse arg seed CBs . /*obtain optional arguments from the CL*/
if datatype(seed,'W') then call random ,,seed /*SEED given for RANDOM repeatability? */
Line 2,323:
@.r.f= x /*put random piece. */
!.r.f= ux; return /* " " " upper*/
end /*#*/ /*#: isn't incremented.*/</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here: &nbsp; ───► &nbsp; [[CHANGESTR.REX]]. <br><br>
'''output''' &nbsp; showing five chess positions (starting with a specific position by seeding the &nbsp; '''random''' &nbsp; BIF with &nbsp; '''96'''),
Line 2,390:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
def hasNK( board, a, b )
for g in -1 .. 1
Line 2,446:
puts
end
</syntaxhighlight>
</lang>
{{out}}<pre>
1bN1RK2/1Pp1pQbP/p2PpP2/8/1pkNP3/P1r1Pp1p/Bn1RPp1r/3qB3 w - - 0 1
Line 2,460:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::fmt::Write;
 
use rand::{Rng, distributions::{Distribution, Standard}};
Line 2,546:
let b: Board = rand::random();
println!("{}", b.fen());
}</langsyntaxhighlight>
 
{{out}}
Line 2,561:
=={{header|Scala}}==
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/zdG9NQ4YSaShFRU7AS31GA Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">import scala.math.abs
import scala.util.Random
 
Line 2,633:
println(createFen)
 
}</langsyntaxhighlight>
 
=={{header|Typescript}}==
{{trans|Java}}
<langsyntaxhighlight lang="typescript">
class Fen {
 
Line 2,717:
let fen: Fen = new Fen();
console.log(fen.createFen());
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,726:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
Line 2,798:
}
 
System.print(createFen.call())</langsyntaxhighlight>
 
{{out}}
Line 2,816:
=={{header|Yabasic}}==
{{trans|C}}
<langsyntaxhighlight Yabasiclang="yabasic">dim grid(8, 8)
sub placeKings()
Line 2,885:
createFen()
</syntaxhighlight>
</lang>
 
=={{header|zkl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="zkl">fcn pickFEN{
# First we chose how many pieces to place: 2 to 32
n := (0).random(2,33);
Line 2,926:
while(re.search(str,1)){ n,m:=re.matched[0]; str=String(str[0,n],m,str[n+m,*]) }
str
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">do(5){ pickFEN().println() }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,935:
5b2/1R6/r4b1q/3Q4/8/8/8/5b2 w - - 0 1
8/1BQ5/8/1q6/1q6/3B1Rq1/5b2/3N3R w - - 0 1</pre>
 
=={{header|ZX Spectrum Basic}}==
A few traps to prevent positions with the wrong number of pieces (not required by the task description but it's worth the effort if we want to use this in a modular way later).
 
<syntaxhighlight lang="zxbasic">
1 DEF FN r(v)=INT (RND*v)+1: REM we'll be using this a lot here for setup, although in real chess it should barely be used at all...
 
10 GO SUB 9400: REM modularity is pretty much vital in making Sinclair BASIC legible
20 GO SUB 9100
30 GO SUB 9200
40 GO SUB 8800
50 GO TO 9500
 
8799 REM Material assignment
8800 LET b=FN r(16)-1: REM give black and white a random number of additional pieces each
8810 LET w=FN r(16)-1
8820 FOR x=1 TO b
8830 LET p=LEN b$
8840 LET k=FN r(p)
8850 LET r=FN r(8): REM defined functions can have the same name as variables
8860 LET f=FN r(8)
8870 IF d$(r,f)<>" " THEN GO TO 8840: REM piece already there
8880 IF b$(k)="p" AND (r=1 OR r=8) THEN GO TO 8840: REM pawn on 1st or 8th rank trapping
8890 LET d$(r,f)=b$(k)
8900 IF k=p THEN LET b$=b$(1 TO k-1): GO TO 8920
8910 LET b$=b$( TO k-1)+b$(k+1 TO )
8920 NEXT x
8930 FOR x=1 TO w: REM now doing for white what we just did for black, could be tidied
8940 LET p=LEN w$
8950 LET k=FN r(p)
8960 LET r=FN r(8)
8970 LET f=FN r(8)
8980 IF d$(r,f)<>" " THEN GO TO 8950
8990 IF w$(k)="P" AND (r=1 OR r=8) THEN GO TO 8950
9000 LET d$(r,f)=w$(k)
9010 IF k=p THEN LET w$=w$(1 TO k-1): GO TO 9030
9020 LET w$=w$( TO k-1)+w$(k+1 TO )
9030 NEXT x
9040 RETURN
 
9099 REM Kings
9100 LET rw=FN r(8)
9110 LET fw=FN r(8)
9120 LET d$(rw,fw)="K"
9130 LET rb=FN r(8)
9140 LET fb=FN r(8)
9150 LET rd=ABS (rw-rb): REM find distance between kings
9160 LET fd=ABS (fd-fb)
9170 IF rd<2 AND fd<2 THEN GO TO 9130
9180 LET d$(rb,fb)="k"
9190 RETURN
 
9199 REM Promotions
9200 FOR b=1 TO 8
9210 LET v=FN r(30): REM 30% chance of promoting each pawn
9220 IF v=1 THEN LET b$(7+b)="q": GO TO 9260
9230 IF v<3 THEN LET b$(7+b)="r": GO TO 9260
9240 IF v<7 THEN LET b$(7+b)="n": GO TO 9260
9250 IF v<10 THEN LET b$(7+b)="b"
9260 NEXT b
9270 FOR w=1 TO 8
9280 LET v=FN r(30)
9290 IF v=1 THEN LET w$(7+w)="Q": GO TO 9330
9300 IF v<3 THEN LET w$(7+w)="R": GO TO 9330
9310 IF v<7 THEN LET w$(7+w)="N": GO TO 9330
9320 IF v<10 THEN LET w$(7+w)="B"
9330 NEXT b
9340 RETURN
 
9399 REM Setup
9400 LET b$="qrrnnbbpppppppp": REM we'll set the kings specifically later
9410 LET w$="QRRNNBBPPPPPPPP"
9420 DIM d$(8,8): REM string arrays are autofilled with spaces; this defines the board area
9430 LET f$=""
9440 LET g$=""
9450 RETURN
 
9499 REM Board
9500 FOR x=1 TO 8
9510 PRINT 9-x;: REM rank number
9520 FOR y=1 TO 8
9530 PRINT INVERSE (((x+y)/2)<>INT ((x+y)/2));d$(x,y);: REM evaluates to 1, a black square, if rank number + file number, read from the top left, is odd; the bottom right square is 8 + 8 = 16 = even = white, conforming to "white to the right" standards
9540 LET f$=f$+d$(x,y): REM building the FEN
9550 NEXT y
9560 PRINT ': REM newline
9570 LET f$=f$+"/"
9580 NEXT x
9590 PRINT " abcdefgh"''
9600 LET k=LEN f$: REM f$ now contains the full string of the board, but we need to count the spaces into numbers
9610 LET t=0: REM counter variable
9620 FOR x=1 TO k
9630 LET t$=f$(x)
9640 IF t$<>" " AND t=0 THEN GO TO 9670: REM not empty and not currently running through blank spaces
9650 IF t$=" " THEN LET t=t+1: GO TO 9670: REM number of blanks in this batch so far
9660 LET f$(x-1)=STR$ t: LET t=0: REM not empty, so a blank space sequence must have ended; insert the counter into the string (STR$ turns the numeric value into its string representation)
9670 NEXT x
9680 FOR x=1 TO k: REM now strip the spaces out
9690 IF f$(x)<>" " THEN LET g$=g$+f$(x)
9700 NEXT x
9710 LET g$=g$( TO LEN g$-1)+" w - - 0 1": REM knock off the final /
9720 PRINT g$</syntaxhighlight>
 
{{out}}
Inverted squares aren't shown here.
<pre>
8..b.....
7N.....R.
6.Q.P..PB
5....R...
4P..R.Nk.
3PRP.....
2K..P....
1........
abcdefgh
 
2B5/N5R1/1Q1P2PB/4R3/P2R1Nk1/PRP
5/K2P4/8 w - - 0 1
 
0 OK, 9720:1
</pre>
77

edits