Sunday, January 9, 2022

A simplified Tic-Tac-Toe implementation in Python

Introduction

A simplified version of the TicTacToe game has been written in Python. This was done as part of a lab in the "PCAP - Programming Essentials In Python" course on Cisco Networking Academy (https://www.netacad.com/portal/learning).

The program showcases the use of:
    1. Tuples
    2. Dictionaries
    3. Two Dimensional Lists
    4. while Loop
    5. if statement
    6. functions

Assumption: The computer always starts with an X in the middle of the board.

Also, the board of the game is numbered from 1 to 9 with position 5 containing the X that represents the first move of the computer.  The initial state of the board will be as per Figure 1.

Figure 1: Initial state of the board.


Algorithm

Taking into consideration the above assumption, the steps to be executed are as follows:
    1. The board is displayed.
    2. User enters a number between 1 to 9 where the 'O' is to be placed.
    3. The updated board is displayed.
    4. If user has won or there is a tie, stop the game.
    5. The computer plays its move.
    6. The updated board is displayed.
    7.  If the computer has won or there is a tie, stop the game.

Note: Steps 2 to 7 are executed in an infinite loop until there is a winner or there is a tie.

Implementation

The board of the game is represented as a two dimensional list called "board".  It is a 3 by 3 array.

A dictionary, "dict_num_to_tup", is used to translate each position (1 to 9) in the board to its corresponding indices in the 2D array.

The following five functions have been defined:
    1. display_board(board)
            - It displays the current state of the board.
    2. enter_move(board)
            - It allows the user to enter a move.  Some basic validations have been included in the function.
    3. make_list_of_free_fields(board)
            - It determines and build a list of free cells in the board.  The list stores the indices of the free cells in the form of tuples.
    4. victory_for(board, sign)
            - It determines whether the "sign" passed as argument to the function has won the game or not.
    5. draw_move(board)
            - It allows the computer to play a move.  A random number generator function has been used to simulate the move of the computer.

Code

Below is the python code.  Same can also be executed by pressing the "play" button.

No comments:

Post a Comment