Reputation: 49
I have just started learning f# and developed a basic game however, at the moment you specify the cell to play on using a single array. For example to place an X or O on the middle cell, you would type 5 when promoted. I want to change this to accept 1,1
I have listed my source code for the game below
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" )
Upvotes: 0
Views: 877
Reputation: 243051
You can create a 2D array in F# using the array2D
function, so to initialize the cells, you could use:
let cells =
array2D [
[ " "; " "; " " ]
[ " "; " "; " " ]
[ " "; " "; " " ]
]
Now you can access elements using cells.[0, 0]
and modify the values using:
cells.[1, 1] <- "X"
The indices are from 0 to 2 so if you want to iterate over all cells to draw the grid, you need:
printfn "-------------"
for x in 0 .. 2 do
printf "| "
for y in 0 .. 2 do
printf " %s |" cells.[x,y]
printfn "\n--------------"
This should give you all the information about 2D arrays, so that you can change the data structure in your game - there are other ways to improve this, but that's probably question for the Code Review site.
Upvotes: 2