Programming Tic-Tac-Toe in Java


<<Previous | ToC | Next >>

Drawing the Board

So now let's write the display routine. Which one of the five concepts do you need to apply first?

If you said "Output" that's a really good high-level description of what this routine needs to do. But we cannot output the whole board in one command. Well, we can call a subroutine to do that in one line, but now we are writing that subroutine.

C programmers like to try to see how much of a whole program they can get into a single line, but it's unreadable and unmaintainable and really hard to make it work. Don't go there. At least not today, it's cute but not helpful. It's not a skill you want to show to the hiring manager of your next place of employment, they most likely would say "We'll call you," (which is a euphemism for "Don't hold your breath waiting").

Well then, what else? Obviously not input. You wouldn't call it a conditional, would you? There may be conditionals inside this top-level structure, but the whole thing is not a "this or that, but not both" kind of conditional.

Maybe you said "Sequence" so let's see how that works out. Here's the board again, so we can see what needs to be done:

 1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9
After a few plays, some of those numerals will be replaced by Xs and Os, so our display routine needs to accommodate whatever is currently in that square. Here's the whole sequence:
Show first square
Show "|"
Show second square
Show "|"
Show third square
Show "---+---+---"
Show fourth square
Show "|"
Show fifth square
Show "|"
Show sixth square
Show "---+---+---"
Show seventh square
Show "|"
Show eighth square
Show "|"
Show last square
Done


It does the job, but you are lucky that we have only nine TTT squares to display. What if you are doing Snake or Tetris, where you have a hundred or more squares to display? Do you remember when we discussed the difference between sequence and iteration? Sequence is how the real world is, and also how the computer must process it, one square after another, but iteration is how we tell the computer to do a sequence of very similar things.

Do you see any similarities that can be iterated? How about the lines separated by those two horizontal lines, the three rows of the board? We can roll up the three rows into one iteration:

Repeat 3
  Show first square of this row
  Show "|"
  Show next square
  Show "|"
  Show last square of this row
  show "---+---+---"
  Next
Done


Do you see another opportunity for iteration? Can you roll it up into another iteration?

Think about your answer, then turn the page.

<<Previous | ToC | Next >>

Revised: 2021 August 30