象棋FEN码转换成矩阵形式
本程序是我项目目的一部分,基本功能是输入一个象棋fen码,比如初始棋局的fen码:“rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR”,将其转化为象棋棋盘矩阵(10行9列),fen码描述棋局很简洁,只是一个字符串,所以很方便通过爬虫提交给象棋ai获取下一步走棋,象棋棋局矩阵就很直观得描述几行几列是什么棋子,方便项目调用,所以本程序就是实现fen转化成matrix。
涉及的知识
看不懂我代码意图没关系,在这里你可以学到
- 正则表达式获取string中的数字,并通过委托二次处理数字,比如我这里用到的,提取数字后,根据数字是几就替换成对应数量的“0”,即“1c5c1”变成“0c00000c0”
- 字符串的分片,以“/”为分割符,把fen码分割成字符串数组
- 矩阵赋值和矩阵打印
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR";
char[,] Matrix = new char[10, 9];
// 创建正则表达式模式
string pattern = @"\d";
// 创建 Regex 对象
Regex regex = new Regex(pattern);
// 使用 MatchEvaluator 方法进行替换
string result = regex.Replace(input, new MatchEvaluator(ReplaceWithZeros));
// 使用 "/"分割字符串
string[] resultsplit = result.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
for (int x=0;x<resultsplit.Length;x++)
{
//Console.WriteLine("{0} is {1}",x, resultsplit[x]);
for (int y = 0; y < resultsplit[x].Length; y++)
{
Matrix[x,y]=resultsplit[x][y];
// Console.WriteLine("{0}{1} is {2}", x,y, resultsplit[x][y]);
}
}
//打印棋盘矩阵
for (int X = 0; X < 10; X++)
{
//write a line from the first matrix
for (int Y = 0; Y < 9; Y++)
Console.Write("{0} ", Matrix[X, Y]);
//add some spaces for visual separation
Console.Write("\t\t");
Console.WriteLine();
}
Console.ReadKey();
}
static string ReplaceWithZeros(Match match)
{
string digits = match.Value;
string zeros = new string('0', Convert.ToInt32(digits));
return zeros;
}
}
运行结果
rnbakabnr/000000000/0c00000c0/p0p0p0p0p/000000000/000000000/P0P0P0P0P/0C00000C0/000000000/RNBAKABNR
r n b a k a b n r
0 0 0 0 0 0 0 0 0
0 c 0 0 0 0 0 c 0
p 0 p 0 p 0 p 0 p
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
P 0 P 0 P 0 P 0 P
0 C 0 0 0 0 0 C 0
0 0 0 0 0 0 0 0 0
R N B A K A B N R