In all of my different implementations of Tic Tac Toe so far I have used a very similar type of data structure to hold the spaces of the board. It has always been an array that holds data like so:
spaces = [1, 2, "X", 3, "O", 5, 6, 7, 8]
Though it is slightly different in Java as it is a statically typed language, so using all strings:
List<String> spaces = new ArrayList<>(Arrays.asList("1", "2", "X", "3", "O", "5", "6", "7", "8"))
Either of which would printed to the command line as:
1 | 2 | X ----------- 4 | O | 6 ----------- 7 | 8 | 9
In my last IPM, my mentors challenged me to store my data differently, noting that I only need the numbers for the empty spaces to display to the user in the command line application.
In this iteration I’ve chosen to keep the array similar and replace the numbers with nil values until it comes time to display the board on the command line.
Now when I create the empty array it is done withArray.new(9) and when I check if a space is empty, I check if a value does not exist in that space.
When it comes to displaying it to the user it has gotten a little more complex. I took some time to play around in Pry and saw that I could make it work by using a .each_with_index and a .map together to display the content of in the space if it exists, otherwise to show the index of the array at that space.
spaces.each_with_index.map !space.nil? ? space : index