12.3 Tic-Tac-Toe

When two players initiate a game of tic-tac-toe, what is the first thing they do? They draw a board. Therefore, we will worry about the board first. A key object we will need is a Board object that stores the tic-tac-toe board. Think about the properties of such a board. A board is typically a large square made up of 3  × 3 smaller squares. At the start of the game all the little squares will be empty, but later they will be filled in with X’s and O’s as the game progresses. Therefore, we will need a 3  × 3 array that is initially empty and can be filled in later while the game is being played. Using objects, we will be able to design the board construction.

Gem of Wisdom

In Example 12-1, we use a shorthand way of declaring an array and its members. Array.new(5) { 3 } creates an array of five elements, with each value initialized to 3. Lines 8–10 declare an array (line 8), with each element being an array initialized to EMPTY_POS (line 9).

Using our knowledge of arrays and objects, we are able to set up the board constructor as shown in Example 12-1.

Example 12-1. Initial board and constructor
     1 class Board
     2 
     3 	BOARD_MAX_INDEX = 2
     4 	EMPTY_POS = ' '
     5 
     6 	def initialize(current_player)
     7 		@current_player = current_player
     8 		@board  = Array.new(BOARD_MAX_INDEX + 1) {
     9 			Array.new(BOARD_MAX_INDEX + 1) { EMPTY_POS }
    10 		}
    11 	end
    12 end
  • Line 3 defines the largest index (remember, array indices start at 0).

  • Line 4 defines what is considered an empty position, or a position ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.