place_kings <- function(brd){
  
  
  
  
  while (TRUE) {
    
    rank_white <- sample(1:8, 1) ; file_white <- sample(1:8, 1)
    rank_black <- sample(1:8, 1) ; file_black <- sample(1:8, 1)
    
    diff_vec <- c(abs(rank_white - rank_black), abs(file_white - file_black))
    
    if (sum(diff_vec) > 2 | setequal(diff_vec, c(0,2))) {
      brd[rank_white, file_white] <- "K"
      brd[rank_black, file_black] <- "k"
      break
    }
  }
  return(brd)
}

pawn_on_extreme_ranks <- function(pc, pr){
  
  
  
  
  if (pc %in% c("P","p") & pr %in% c(1,8))
    return(TRUE)
  else
    return(FALSE)
}

populate_board <- function(brd, wp, bp){
  
  
  
  
  
  piece_list <- c("P", "N", "B", "R", "Q")
  for (color in c("white", "black")){
    
    if (color == "white"){
      n_pieces = wp
      pieces = piece_list
    }
    else {
      n_pieces = bp
      pieces = tolower(piece_list)
    }
    
    while (n_pieces != 0){
      piece_rank <- sample(1:8, 1) ; piece_file <- sample(1:8, 1)
      piece <- sample(pieces, 1)
      
      if (brd[piece_rank, piece_file] == " " & !pawn_on_extreme_ranks(piece, piece_rank)){
        brd[piece_rank, piece_file] <- piece
        n_pieces <- n_pieces - 1
      }
    }
  }
  return(brd)
}

fen_from_board <- function(brd){
  
  
  
  
  fen <- apply(brd, 1, function(x) {
    r <- rle(x) 
    paste(ifelse(r$values == " ", r$lengths, r$values), collapse = "")
    })
  
  fen <- paste(paste(fen, collapse = "/"), "w - - 0 1")
  return(fen)
}

generate_fen <- function(){
  
  
  
  
  
  board <- matrix(" ", nrow = 8, ncol = 8)
  
  n_pieces_white <- sample(0:31, 1) ; n_pieces_black <- sample(0:31, 1)
  
  board <- place_kings(board)
  
  board <- populate_board(board, wp = n_pieces_white, bp = n_pieces_black)
  
  print(board)
  cat("\n")
  cat(fen_from_board(board))
}

generate_fen()