我刚刚开始学习f#并开发了一个基本游戏,但是当你指定要使用单个数组播放的单元格时。例如,要在中间单元格上放置X或O,您可以在提升时键入5。我想将此更改为接受1,1
我列出了下面游戏的源代码
let arrayOfCells = [|" "; " "; " "; " "; " "; " "; " "; " " ;" "|]
let drawGrid()=
Console.Write("\n\n\t\t" + arrayOfCells.[0] + "|" + arrayOfCells.[1]+ "|" + arrayOfCells.[2] + "\n" )
Console.Write("\t\t------ "+ "\n" )
Console.Write("\t\t" + arrayOfCells.[3] + "|" + arrayOfCells.[4]+ "|" + arrayOfCells.[5] + "\n" )
Console.Write("\t\t------ "+ "\n" )
Console.Write("\t\t" + arrayOfCells.[6] + "|" + arrayOfCells.[7]+ "|" + arrayOfCells.[8] + "\n" )
答案 0 :(得分:2)
您可以使用array2D
函数在F#中创建2D数组,因此要初始化单元格,您可以使用:
let cells =
array2D [
[ " "; " "; " " ]
[ " "; " "; " " ]
[ " "; " "; " " ]
]
现在您可以使用cells.[0, 0]
访问元素并使用以下内容修改值:
cells.[1, 1] <- "X"
索引从0到2,因此如果要迭代所有单元格以绘制网格,则需要:
printfn "-------------"
for x in 0 .. 2 do
printf "| "
for y in 0 .. 2 do
printf " %s |" cells.[x,y]
printfn "\n--------------"
这应该为您提供有关2D数组的所有信息,以便您可以更改游戏中的数据结构 - 还有其他方法可以改善这一点,但这可能是the Code Review site的问题。< / p>