0

试图建立一个有效的FEN 字符串

给定这个 8*8 数组示例,表示棋盘,(“1”是空方格):

$checkerboard = [["r","n","b","q","k","b","n","r"],["p","p","p","p","p","p","p","p"],["1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1"],["1","1","1","1","P","1","1","1"],["1","1","1","1","1","1","1","1"],["P","P","P","P","1","P","P","P"],["R","N","B","Q","K","B","N","R"]]

在现场,这是位置:

在此处输入图像描述

我正在寻找的有效结果是:

rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR

现在我的输出是:

rnbqkbnr/pppppppp/11111111/11111111/1111P111/11111111/PPPP1PPP/RNBQKBNR

显然,数组中的任何整数条目都应该与下一个条目相加,只有当下一个条目是整数时,才应该丢弃下一个条目直到结束

通过迭代数组,我不确定如何以简单的方式在这里应用array_walk()array_map() 之类的东西。也许一个简单的字符串操作就足够了?

  $FEN = "";
  for ($i = 0;$i < 8;$i++){
    for ($j = 0;$j < 8;$j++){
      if ($checkerboard[$i][$j] === "1"){
        if ($checkerboard[$i][$j + 1] === "1"){
           /* How to iterate till the end */
           $FEN .= (int)$checkerboard[$i][$j] + (int)$checkerboard[$i][$j+1];
        }
      } else {
        $FEN .= $checkerboard[$i][$j];
      }      
    }
    $FEN .= "/";
  }

有什么见解吗?

在线示例: https ://3v4l.org/tuqqo

4

1 回答 1

2
$checkerboard = [["r","n","b","q","k","b","n","r"],["p","p","p","p","p","p","p","p"],["1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1"],["1","1","1","1","P","1","1","1"],["1","1","1","1","1","1","1","1"],["P","P","P","P","1","P","P","P"],["R","N","B","Q","K","B","N","R"]];

$parts =  array();
foreach ($checkerboard as $innerArray) {
    $num = null;
    $str = '';
    foreach($innerArray as $innerval){
        if(is_numeric($innerval)){
            $num += (int) $innerval;
        }
        else{
            if(!is_null($num)){
                $str .=$num;
                $num = null;
            }
            $str .=$innerval;
        }
    }
    if(!is_null($num)){
        $str .=$num;
    }
    array_push($parts,$str);
}
$result = implode('/',$parts);

上面的代码将生成所需的输出并将其存储在 $result 中。

于 2019-10-09T03:41:34.397 回答