我一直在Ocaml中键入一个代码,该类存储象棋棋盘位置(棋子,颜色,位置)的数组。我需要编写一种方法以8x8字符串格式将其打印出来。我的代码给出错误,我该怎么做?
我实际上已经考虑过制作一个数组矩阵并将值放入其中,但是我不知道如何按位置匹配每个片段,所以我想出了一个模式,用于匹配字符串的各个片段,但是我不认为这是最好的解决方案。到目前为止,我编写了以下代码:
type chess_letter = A | B | C | D | E | F | G | H
and chess_piece = King | Queen | Rook | Bishop | Knight | Pawn
and chess_colour = Black | White
and chess_position = Alive of chess_letter * int | Dead
class chess =
object (self)
val number_of_players = 2
val first_player = White
val board = Array.make_matrix 8 8 None
val pieces_on_board = [|(Rook, Black, Alive (A,8)); (Knight, Black, Alive (B,8)); (Bishop, Black, Alive (C,8)); (Queen, Black, Alive (D,8));
(King, Black, Alive (E,8)); (Bishop, Black, Alive (F,8)); (Knight, Black, Alive (G,8)); (Rook, Black, Alive (H,8));
(Pawn, Black, Alive (A,7)); (Pawn, Black, Alive (B,7)); (Pawn, Black, Alive (C,7)); (Pawn, Black, Alive (D,7));
(Pawn, Black, Alive (E,7)); (Pawn, Black, Alive (F,7)); (Pawn, Black, Alive (G,7)); (Pawn, Black, Alive (H,7));
(Pawn, White, Alive (A,2)); (Pawn, White, Alive (B,2)); (Pawn, White, Alive (C,2)); (Pawn, White, Alive ( D,2));
(Pawn, White, Alive (E,2)); (Pawn, White, Alive (F,2)); (Pawn, White, Alive (G,2)); (Pawn, White, Alive (H,2));
(Rook, White, Alive (A,1)); (Knight, White, Alive (B,1)); (Bishop, White, Alive (C,1)); (Queen, White, Alive (D,1));
(King, White, Alive (E,1)); (Bishop, White, Alive (F,1)); (Knight, White, Alive (G,1)); (Rook, White, Alive (H,1))|]
method put_pieces_on_board pieces_on_board = match pieces_on_board with
| (Rook, White, Alive (chess_letter, int)) -> "R" | (Knight, White, Alive (chess_letter, int)) -> "N"
| (Bishop, White, Alive (chess_letter, int)) -> "B" | (Queen, White, Alive (chess_letter, int)) -> "Q"
| (King, White, Alive (chess_letter, int)) -> "K" | (Pawn, White, Alive (chess_letter, int)) -> "P"
| (Rook, Black, Alive (chess_letter, int)) -> "r" | (Knight, Black, Alive (chess_letter, int)) -> "n"
| (Bishop, Black, Alive (chess_letter, int)) -> "b" | (Queen, Black, Alive (chess_letter, int)) -> "q"
| (King, Black, Alive (chess_letter, int)) -> "k" | (Pawn, Black, Alive (chess_letter, int)) -> "p"
| (Rook, White, Dead) -> "." | (Knight, White, Dead) -> "."
| (Bishop, White, Dead) -> "." | (Queen, White, Dead) -> "."
| (King, White, Dead) -> "." | (Pawn, White, Dead) -> "."
| (Rook, Black, Dead) -> "." | (Knight, Black, Dead) -> "."
| (Bishop, Black, Dead) -> "." | (Queen, Black, Dead) -> "."
| (King, Black, Dead) -> "." | (Pawn, Black, Dead) -> "."
method print = print_string(string_of_string self#put_pieces_on_board ^ "---" )
end;;
非常感谢您提前回答。
答案 0 :(得分:0)
当我尝试编译您的代码时,我抱怨没有定义string_of_string
。但这很可能不是您要问的错误。
您想遍历数组并为每个元素调用self#put_pieces_on_board
。
执行此操作的一个函数是Array.map
,它将为您提供字符串数组。您可以使用Array.to_list
将其转换为列表,然后使用String.concat
获得一个大字符串。但是,仍然需要做一些工作才能制作出漂亮的8x8网格。
method print =
Array.map self#put_pieces_on_board pieces_on_board |>
Array.to_list |>
String.concat " "
我不确定这是否是您要的内容,但也许会有所帮助。