12.4 Tic-Tac-Toe Revised

Although a player-versus-player version of tic-tac-toe is nice, chances are you will not have a friend who wants to spend time playing computerized tic-tac-toe with you for long. Perhaps it will be more satisfying if you create a version of tic-tac-toe that will play against you. This is what we will do in this section.

First, let’s understand the change we are trying to make. Instead of always having the player input the position on the board to fill, we want the computer to take one of the turns. Therefore, we will make a clearer distinction between the human’s move and the computer’s move. The code in Example 12-13 illustrates this change.

Example 12-13. Revised ask_player_for_move method
    1 def ask_player_for_move(current_player)
    2 	if current_player == COMPUTER_PLAYER
    3 		computer_move(current_player)
    4 	else
    5 		human_move(current_player)
    6 	end
    7 end

The purpose of the ask_player_for_move method is to switch between player input and computer AI (artificial intelligence) based on the current player. If the current player is the computer (line 2), let the computer take its move (line 3); otherwise (line 4), let the user take her or his move (line 5). Make sure to define the constant COMPUTER_PLAYER. It may be set equal to X or O. This would also be a good time to define the constant HUMAN_PLAYER. This should be set equal to O if COMPUTER_PLAYER is equal to X, or X if COMPUTER_PLAYER is equal to O.

If you have been reading carefully, you will have noticed ...

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.