Programming Tic-Tac-Toe in Java


<<Previous | ToC | Next >>
 

Displaying the Board and Keeping Score

The first stage is to keep score and display the game.

Keeping score consists mainly in showing where each X and O has been played (which is part of displaying the board), and recognizing if a player has achieved three in a row. Somewhere in there the players actually enter their plays for the computer to record.

At the highest level, we have an iteration:

Initialize board
Repeat 9 times
  Show current board
  Input play
  Update board
  Test for win
  If so, exit
  Next
Say who won
Show current board


I wrote this in the Kitchen computer dialect of English so I can check my work as I go. Except I'm not ready to do that, there are several vague descriptors of what needs to be done. I can make them into stub subroutines for now:

"Initialize board"
  print "Initialize board"

"Show current board"
  print "Show current board"

"Update board"
  print "Update board"

"Test for win"
  print "Test for win"


If you put this together and run it in the English computer, it will print out the three lines nine times, pausing for you to input something each time, but ignoring the result. First it might complain about not knowing what "who" and "won" mean.

Just to keep things simple, I will

let who = "X"
as part of the initialization, and that variable will be which player is going to play. Then put quotes around "won".

This program (as written) might also behave erratically in the line 'If so, exit' but you could temporarily stub it out or replace "so" with "false". It needs to be clarified when we get around to testing for a win (see explantion here).

Doing this in Kitchen is not a necessary part of programming this "Keeping Score" but writing it up in English is a great help in getting one's thoughts in line.
 

Data Structures

Before we can display or update the board, we need to know what the board looks like, and more importantly, what kind of variable to use. Tic-Tac-Toe is played on a 3x3 square board, which (when it is useful, like today) is commonly numbered from 1 to 9, like so:
 1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9


Actually, the lines on a real board are solid. This is sort of a hint at how we will display the board in ASCII graphics. Later, when we do it in the GameEngine, we can use solid lines. Each time somebody plays, we replace that square's number with the X or O that was played there. Whenever the human plays, they will type in a single digit (or in the GameEngine, click on that square, in which case you don't need to show numbers), and the computer can then update the board from that input.

So what kind of variable can we use to keep track of who played where? Think about your answer, then turn the page.

<<Previous | ToC | Next >>

Revised: 2021 September 13