Task: Generate random chess position




Go: package main

import (
    "fmt"
    "math/rand"
    "strconv"
    "strings"
    "time"
)

var grid [8][8]byte

func abs(i int) int {
    if i >= 0 {
        return i
    } else {
        return -i
    }
}

func createFen() string {
    placeKings()
    placePieces("PPPPPPPP", true)
    placePieces("pppppppp", true)
    placePieces("RNBQBNR", false)
    placePieces("rnbqbnr", false)
    return toFen()
}

func placeKings() {
    for {
        r1 := rand.Intn(8)
        c1 := rand.Intn(8)
        r2 := rand.Intn(8)
        c2 := rand.Intn(8)
        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
            grid[r1][c1] = 'K'
            grid[r2][c2] = 'k'
            return
        }
    }
}

func placePieces(pieces string, isPawn bool) {
    numToPlace := rand.Intn(len(pieces))
    for n := 0; n < numToPlace; n++ {
        var r, c int
        for {
            r = rand.Intn(8)
            c = rand.Intn(8)
            if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
                break
            }
        }
        grid[r][c] = pieces[n]
    }
}

func toFen() string {
    var fen strings.Builder
    countEmpty := 0
    for r := 0; r < 8; r++ {
        for c := 0; c < 8; c++ {
            ch := grid[r][c]
            if ch == '\000' {
                ch = '.'
            }
            fmt.Printf("%2c ", ch)
            if ch == '.' {
                countEmpty++
            } else {
                if countEmpty > 0 {
                    fen.WriteString(strconv.Itoa(countEmpty))
                    countEmpty = 0
                }
                fen.WriteByte(ch)
            }
        }
        if countEmpty > 0 {
            fen.WriteString(strconv.Itoa(countEmpty))
            countEmpty = 0
        }
        fen.WriteString("/")
        fmt.Println()
    }
    fen.WriteString(" w - - 0 1")
    return fen.String()
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(createFen())
}




Python: import random

board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]


def place_kings(brd):
	while True:
		rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
		diff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]
		if sum(diff_list) > 2 or set(diff_list) == set([0, 2]):
			brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k"
			break

def populate_board(brd, wp, bp):
	for x in range(2):
		if x == 0:
			piece_amount = wp
			pieces = piece_list
		else:
			piece_amount = bp
			pieces = [s.lower() for s in piece_list]
		while piece_amount != 0:
			piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)
			piece = random.choice(pieces)
			if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False:
				brd[piece_rank][piece_file] = piece
				piece_amount -= 1

def fen_from_board(brd):
	fen = ""
	for x in brd:
		n = 0
		for y in x:
			if y == " ":
				n += 1
			else:
				if n != 0:
					fen += str(n)
				fen += y
				n = 0
		if n != 0:
			fen += str(n)
		fen += "/" if fen.count("/") < 7 else ""
	fen += " w - - 0 1\n"
	return fen

def pawn_on_promotion_square(pc, pr):
	if pc == "P" and pr == 0:
		return True
	elif pc == "p" and pr == 7:
		return True
	return False


def start():
	piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)
	place_kings(board)
	populate_board(board, piece_amount_white, piece_amount_black)
	print(fen_from_board(board))
	for x in board:
		print(x)


start()