Tic Tac Toe program in cpp

Beginners code hub
By -
0
# Define the board
board = [' ' for _ in range(9)]

def print_board():
    print('\n')
    print(f' {board[0]} | {board[1]} | {board[2]}')
    print('---|---|---')
    print(f' {board[3]} | {board[4]} | {board[5]}')
    print('---|---|---')
    print(f' {board[6]} | {board[7]} | {board[8]}')
    print('\n')

def is_winner(player):
    return (
        (board[0] == board[1] == board[2] == player) or 
        (board[3] == board[4] == board[5] == player) or 
        (board[6] == board[7] == board[8] == player) or 
        (board[0] == board[3] == board[6] == player) or 
        (board[1] == board[4] == board[7] == player) or 
        (board[2] == board[5] == board[8] == player) or 
        (board[0] == board[4] == board[8] == player) or 
        (board[2] == board[4] == board[6] == player)
    )

def is_draw():
    return all(cell != ' ' for cell in board)

def play_game():
    print_board()
    for turn in range(9):
        player = 'X' if turn % 2 == 0 else 'O'
        print(f'Player {player}, make your move (1-9): ', end='')
        move = int(input()) - 1
        if board[move] == ' ':
            board[move] = player
            print_board()
            if is_winner(player):
                print(f'Player {player} wins!')
                return
            elif is_draw():
                print('It\'s a draw!')
                return
        else:
            print('Invalid move. Try again.')
            continue

play_game()
    

Functions in the Program


Functions are essential to make the code reusable and modular. The following functions are commonly used:


1. print_board()


Purpose: Displays the game board with the current state.


How it works: It formats the board list into a 3x3 grid and prints it.


Why it's useful: Keeps the game visually clear for players.




2. is_winner(player)


Purpose: Checks if the specified player ('X' or 'O') has won.


How it works: Compares specific combinations (rows, columns, diagonals) of the board list to see if they match the player's symbol.


Why it's useful: Determines the winner after each move.




3. is_draw()


Purpose: Checks if the board is full and no player has won.


How it works: Uses a loop or condition to see if there are no empty spaces (' ') left in the board.


Why it's useful: Ends the game in case of a draw.




4. play_game()


Purpose: Manages the entire gameplay process.


How it works:


Alternates between Player 1 ('X') and Player 2 ('O').


Takes input, validates it, and updates the board.


Calls functions to check for winners or draws.



Why it's useful: Centralizes the game logic for better organization.


Important Keywords


1. def

Used to define a function.


2. if, elif, else


Control the flow of the program based on conditions.


3. for, range


Loops to iterate through moves or position

4. return


Exits a function and optionally sends a value back to the caller.


Data Structures


1. List (board)


Used to represent the 3x3 grid.


Each index corresponds to a cell on the board.

1. player Alternation


Alternates between Player 1 ('X') and Player 2 ('O') using a loop.


2. Winning Combinations


Specific indexes on the board list represent winning lines:


Rows: [0, 1, 2], [3, 4, 5], [6, 7, 8]


Columns: [0, 3, 6], [1, 4, 7], [2, 5, 8]


Diagonals: [0, 4, 8], [2, 4, 6]


3. Input Validation


Ensures the player's move is valid:


The number must be within range (1-9).


The chosen cell must be empty.


Sample output

Tic Tac Toe program in cpp



Tags:

Post a Comment

0Comments

Post a Comment (0)