Coders Packet

Tic Tac Toe in python

By Preetha P

Tic Tac Toe in python is implemented using different user-defined functions and loops. Generally, it takes in user input, checks for the specific condition and prints the winner as output.

In this python project, we will create different functions:

Function 1: This is a function that can print out a board(3x3). 

def board_disp(board):

 

Function 2: This is a function takes in a player's input and assign their marker m as 'X' or 'O'.

def player_value():

 

Function 3: This is a function takes in the board list object, a marker m ('X' or 'O'), and a desired position and assigns it to the board.

def board_marker(board, m, position):

 

Function 4: This is a function takes in a board and checks, if someone has won.

def check(board,mark):

 

Function 5: This function uses the random module to randomly decide which player goes first. Here we use random.randint() to return a string of which player went first.

def first():

 

Function 6: This function that returns a Boolean indicating whether a space is available.

def space_check(board, position):

 

Function 7: This function that checks if the board is full and returns a boolean value. True if full, False otherwise.

def full_board_check(board):

 

Function 8: This function that asks for a player's next position ( 1-9) and then uses the function 6 to check if it is a free position. If it is, then return the position.

def player_choice(board):

 

Function 9: This function asks the player if they want to play again and returns a boolean True if they do want to play again.

def replay():

 

Final step: Use while loops and the functions you have created and combine all of these ideas to form a game logic.

Here, we first get an input from the user and assigning the ‘m’ as ‘X’ or ‘O’ and we randomly decide which player to goes first using random module. Now, the function takes in the desired position from the player and checks if the space is empty/available and if its available it is assigned to the board.

Next, it checks for the condition if someone has won (vertically, horizontally, diagonally) using the defined check() function. If the winning condition is true, it prints the winner as output. Or else if the board is full (no space) and the winning condition is not satisfied, then it returns draw.

Finally, the replay() function ask the player if they want to play again and returns a boolean True if they do want to play again.

 

Output:

Output

 

Output

Download project

Reviews Report

Submitted by Preetha P (Preetha11)

Download packets of source code on Coders Packet