0% found this document useful (0 votes)
121 views15 pages

Rebort Tic Tac Toe

Uploaded by

Esmael Elkot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views15 pages

Rebort Tic Tac Toe

Uploaded by

Esmael Elkot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Assiut University

Faculty of Science

Artificial Intelligence Course (CS361)

OUR TEAM:

NAME : YOUSSEF MOHAMED ABDELRAZEK. ID : 120200635

NAME : MOSTAFA ABDELHAMED ID : 120200494

NAME : MOHAMED ESSAM ELDIN ID : 120200678

NAME : ERIC MAGED BISHOT ID : 120200112

NAME: ABDELRAHMAN HESHAM ID : 120200320


Using The BFS(Breadth First Search) To Solve The Tic-Tac-Toe Problem

1.INTRODUCTION/EXECUTIVE SUMMARY:……………………………………………………………………………………

1.1 Tic-Tac-Toe :……………………………………………………………………………………………………………………….

1.2 Tic-Tac-Toe solver algorthms :…………………………………………………………………………………………….

1.3 Algorithm Selection :………………………………………………………………………………………………………….

2.METHODOLOGY :………………………………………………………………………………………………………………………

2.1 What is bfs ? :..…………………………………………………………………………………………………………………….

2.2 The steps of the BFS (Breadth-First Search) algorithm are as :………………………………………..……

2.3 BFS FlowChart :.…………………………………………………………………………………………………………………..

2.4 BFS Pseudo-code :.………………………………………………………………………………………………………………

2.5 solving Tic-Tac-Toe using the BFS algorithm :……………………………………………………………………..

3.EXPERIMENTAL SIMULATION:………………………………………………………………………………………………………

4.RESULTS:.……………………………………………………………………………………………………………………………………

5.CONCLUSIONS:……………………………………………………………………………………………………………………………

6.REFERENCES………………………………………………………………………………………………………………………………..

7.SOURCE CODE……………………………………………………………………………………………………………………………..
INTRODUCTION/EXECUTIVE SUMMARY:

TIC-TAC-TOE :

Tic-Tac-Toe, also known as Noughts and Crosses, is a classic paper-and-pencil game played on a 3x3 grid. The game
involves two players who take turns marking spaces on the grid with their respective symbols, usually "X" and "O".
The objective of the game is to form a horizontal, vertical, or diagonal line of three of their symbols.

The game starts with an empty grid, and the players take turns making their moves. Each player aims to strategically
place their symbol in a way that prevents their opponent from forming a winning line while simultaneously
attempting to create their own winning line. The game continues until one player achieves a winning line or if all
spaces on the grid are filled without a winner, resulting in a draw.

TIC-TAC-TOE SOLVER ALGORTHMS :

1. A* ALGORITHM:

A* is a search algorithm that is often used in pathfinding and graph traversal problems. It combines elements
of both DFS and BFS by using heuristics to prioritize which nodes to explore. A* evaluates nodes based on a
cost function that combines the cost to reach a node from the starting point and a heuristic estimate of the
cost to reach the goal.

2. DEPTH-FIRST SEARCH:

This algorithm explores all possible moves in the game tree using a depth-first search technique. It requires
storing repeated game states to monitor the state and avoid looping.

3. BREADTH-FIRST SEARCH:

This algorithm explores all possible moves in the game tree using a breadth-first search technique. It relies on
using a queue to store potential game states and progressively expand upon them.
ALGORITHM SELECTION:

1. DEPTH-FIRST SEARCH (DFS):

DFS is an algorithm used for traversing or searching tree or graph data structures. It explores as far as possible
along each branch before backtracking. DFS uses a stack to keep track of the nodes to visit. It starts at the root
node and explores as deep as possible until it reaches a leaf node or a node with no unvisited neighbors.

2. BREADTH-FIRST SEARCH (BFS):

BFS is another graph traversal algorithm that explores all the vertices of a graph in breadth-first order,
meaning it visits all the vertices at the same level before moving to the next level. BFS uses a queue to keep
track of the nodes to visit. It starts at the root node, explores all its neighbors, then moves to the next level
and repeats the process until all nodes are visited.

3. A* ALGORITHM:

A* is a search algorithm that is often used in pathfinding and graph traversal problems. It combines elements
of both DFS and BFS by using heuristics to prioritize which nodes to explore. A* evaluates nodes based on a
cost function that combines the cost to reach a node from the starting point and a heuristic estimate of the
cost to reach the goal.

1. Completeness: BFS guarantees that it will find a solution if one exists. In the context of Tic Tac Toe, if there
is a winning move, BFS will find it.

2. Optimal Solution: BFS explores the game state in a breadth-first manner, meaning it will find the optimal
solution with the fewest number of moves required to win.

3. Memory Efficiency: BFS only keeps track of the current level of the search tree, which makes it memory-
efficient compared to algorithms like DFS or A*.

4. Game Complexity: Tic Tac Toe has a relatively small search space, as there are only nine positions on the
board. BFS can efficiently explore all possible moves until a winning move is found.

IN THE CONTEXT OF TIC TAC TOE, BFS IS WELL-SUITED BECAUSE IT GUARANTEES FINDING THE OPTIMAL
SOLUTION (IF IT EXISTS) WHILE KEEPING MEMORY USAGE LOW. THE SMALL SEARCH SPACE OF THE GAME
ALLOWS BFS TO EXPLORE ALL POSSIBLE MOVES SYSTEMATICALLY AND EFFICIENTLY.
METHODOLOGY:

WHAT IS BFS ? :

The Breadth-First Search (BFS) algorithm is a graph traversal algorithm that explores all the vertices of a graph
in breadth-first order, i.e., it explores all the vertices at the same level before moving to the next level. It starts
at a given vertex (or node) of the graph and systematically explores its neighboring vertices before moving to
the neighbors' neighbors.

The algorithm uses a queue data structure to keep track of the vertices that need to be explored. It starts by
enqueueing the initial vertex and marking it as visited. Then, it dequeues a vertex from the queue, visits all its
unvisited neighbors, and enqueues them. This process continues until the queue is empty, indicating that all
vertices have been visited.

BFS is often used to solve problems that require finding the shortest path or exploring all possible states in a
graph. It guarantees that it will find the shortest path between two vertices if one exists. The algorithm is
complete, meaning it will find a solution if one exists, as long as the graph is finite.

THE STEPS OF THE BFS (BREADTH-FIRST SEARCH) ALGORITHM ARE AS:

STEP1: INITIALLY QUEUE AND VISITED ARRAYS ARE EMPTY.

Step2: Push node 0 into queue and mark it visited.


Step 3: Remove node 0 from the front of queue and visit the unvisited neighbours and push them into queue.

Step 4: Remove node 1 from the front of queue and visit the unvisited neighbours and push them into queue.

Step 5: Remove node 2 from the front of queue and visit the unvisited neighbours and push them into queue.

Step 6: Remove node 3 from the front of queue and visit the unvisited neighbours and push them into queue.
As we can see that every neighbours of node 3 is visited, so move to the next node that are in the front of the
queue.
Steps 7: Remove node 4 from the front of queue and visit the unvisited neighbours and push them into queue.
As we can see that every neighbours of node 4 are visited, so move to the next node that is in the front of the
queue.

BFS FLOWCHART:
BFS PSEUDO-CODE :

SOLVING TIC-TAC-TOE USING THE BFS ALGORITHM:

1. Create an empty queue to store game states.

2. Enqueue the initial state of the game board.

3. Start a loop that continues until the queue is empty.

4. Dequeue a game state from the front of the queue.

5. Check if the dequeued state represents a winning move for the AI player ('O'). If it does, return the game state.

6. Check if the game is over (either a win for 'X' or 'O', or a draw). If it is, continue to the next iteration of the loop.

7. Generate all possible next moves from the current game state by finding empty positions on the board.

8. For each possible move, create a new game state by placing the AI player's symbol ('O') in the empty position.

9. Enqueue the new game state to explore it in future iterations.

10. Repeat steps 4 to 9 until a winning move is found or the queue is empty.

11. If the queue becomes empty and no winning move is found, the game is either a draw or a loss for the AI player.

12. Return the final game state as the result.

THESE STEPS ENSURE THAT THE BFS ALGORITHM EXPLORES ALL POSSIBLE GAME STATES IN A BREADTH-FIRST
MANNER, FINDING THE OPTIMAL MOVE FOR THE AI PLAYER BY CONSIDERING ALL POSSIBLE OUTCOMES.
EXPERIMENTAL SIMULATION:

1. The code begins by importing the `random` module and the `deque` class from the `collections` module.
The `random` module is not used in this code snippet, and the `deque` class is used to implement a queue
data structure for the breadth-first search (BFS) algorithm.

2. The Tic Tac Toe board is initialized as a list of empty spaces, represented by blank characters.

3. The `WINNING_COMBINATIONS` variable stores all the possible winning combinations in the Tic Tac Toe
game. It includes the winning combinations for rows, columns, and diagonals on the board.
4. The `BFS_MOVE(BOARD)` function implements the BFS algorithm to find the optimal move for the AI
player ('O'). It starts by initializing a queue using a deque, starting with the initial state of the board and an
initial move of -1. It also creates a set called `visited` to keep track of visited states to avoid revisiting them.

5. The BFS algorithm continues until the queue is empty. In each iteration, it retrieves the state and the last
move from the left side of the queue. It adds the current state to the `VISITED` set.

6. If the current state is a game-over state (EITHER A WIN FOR 'X' OR 'O' OR A DRAW) the last move is
returned as the optimal move for the AI.

7. If the current state is not a game-over state, the algorithm generates all possible next moves by iterating
over each cell of the current state. If a cell is empty, a new state is created by copying the current state and
placing an 'O' in the empty cell. If the new state has not been visited before, it is added to the queue along
with the index of the move.

8. The `IS_WINNER(BOARD, PLAYER)` function checks if a given player has won by iterating through the
winning combinations and checking if all the positions in a combination are occupied by that player.

9. The `IS_DRAW(BOARD)` function checks if the game is a draw by simply checking if there are no empty
spaces left on the board.

10. The `IS_GAME_OVER(BOARD)` function determines if the game is over by checking if either player has
won or if the game is a draw.

11. The `DISPLAY_BOARD(BOARD)` function is responsible for visualizing the Tic Tac Toe board by printing
the board state.
1 The `GET_USER_MOVE()` function prompts the user to enter their move as an integer between 1 and 9. It
validates the input and returns the move as an index in the board list.

2. The `PLAY_GAME()` function is the main game loop. It starts by prompting the user to choose their
opponent ('AI' or 'Player'). It displays the initial board state and continues until there is a winner or a draw. In
each iteration, it gets the move from either the user or the AI based on the chosen opponent. The board is
updated with the move, and the updated board is displayed.

3. After the game loop ends, the outcome of the game is determined by checking if 'X' OR 'O' has won or if
it's a draw, and the appropriate message is printed.

4. Finally, the game is started by calling the `PLAY_GAME()` function.

THIS CODE ASSUMES A SIMPLE USER INPUT MECHANISM, ALTERNATING TURNS BETWEEN THE USER ('X')
AND THE AI PLAYER ('O'(
RESULTS AND TECHNICA L DISCUSSION: :

1: AI PLAY THE GAME:

2: USER PLAY THE GAME :


The "play_game" function starts the game and runs the main game loop until the game is over.

- The user is prompted to choose an opponent, and the initial board is displayed.

- In each iteration of the game loop, the move is obtained from either the user or the AI player, depending on
the chosen opponent.

- Then, the board is updated, displayed, and checked if the game has ended.

- Finally, the winner is determined or a draw is declared, marking the end of the game.

CONCLUSIONS:

USING BREADTH-FIRST SEARCH (BFS) IN A TIC-TAC-TOE GAME CAN HAVE BOTH STRENGTHS AND
WEAKNESSES. LET'S ANALYZE THEM AND PROVIDE CONCLUSIONS:

STRENGTHS OF BFS ALGORITHM IN TIC-TAC-TOE:

1. Completeness: BFS guarantees to find a solution if one exists. In Tic-Tac-Toe, BFS will always find the
optimal move or determine that the game ends in a draw.

2. Optimality: If there is a winning move available, BFS will find it. It explores all possible moves in a systematic
manner, ensuring that the optimal move is chosen.

3. Fairness: BFS treats all game states equally and does not prioritize any specific move. It explores all possible
moves at each level of the game tree, leading to a fair evaluation of the game.

4. Simplicity: The BFS algorithm is relatively easy to understand and implement. It follows a systematic
approach of exploring all possible moves, making it straightforward to apply to Tic-Tac-Toe.

WEAKNESSES OF BFS ALGORITHM IN TIC-TAC-TOE :

1. Time Complexity: The time complexity of BFS grows exponentially with the branching factor and the depth
of the game tree. In Tic-Tac-Toe, the branching factor is 9 (number of empty cells), and the depth can be up to
9 (maximum number of moves). As a result, BFS can become slow and inefficient in more complex games or
situations.

2. Memory Usage: BFS requires storing all explored states in memory. In Tic-Tac-Toe, this means maintaining a
queue or a tree of game states. As the game progresses, the memory requirement can become significant,
especially if the game tree is large.

3. Lack of Game-Specific Knowledge: BFS does not consider any specific strategies or heuristics tailored for
Tic-Tac-Toe. It explores all possible moves uniformly, which can be computationally expensive and
unnecessary in some cases.
PERFORMANCE AND IMPLICATIONS:

In Tic-Tac-Toe, the BFS algorithm performs well in terms of finding the optimal move or determining a draw. It
guarantees a correct and optimal solution. However, its time complexity and memory usage can be limiting
factors, especially for larger game boards or more complex games.

SUCCESSFUL SITUATIONS:

1. Early Game: In the early game, when the number of empty cells is high, BFS can efficiently explore all
possible moves and identify the winning moves or blocking moves.

2. Small Game Boards: For smaller Tic-Tac-Toe boards, where the branching factor and depth are limited, BFS
can perform well and find the optimal moves in a reasonable time.

CHALLENGING SITUATIO NS:

1. Late Game: As the game progresses and fewer empty cells remain, the branching factor decreases, and the
depth of the game tree increases. This can make BFS slower and more memory-intensive, impacting its
performance.

2. Large Game Boards: When the Tic-Tac-Toe board is larger, the number of empty cells increases, leading to a
higher branching factor and deeper game tree. BFS can become inefficient in such cases.

IMPROVING PERFORMANC E:

To improve the performance of the BFS algorithm in Tic-Tac-Toe, some modifications can be considered:

1. Pruning Techniques: Introduce pruning techniques such as alpha-beta pruning to eliminate unnecessary
branches and reduce the search space.

2. Heuristics: Incorporate game-specific heuristics to guide the search towards more promising moves. This
can help in reducing the search space and making the algorithm more efficient.

3. Memoization: Store and reuse previously evaluated game states to avoid redundant computations.

4. Iterative Deepening: Instead of exploring the entire game tree in a single BFS run, use iterative deepening
to limit the search depth gradually, balancing the trade-off between time and optimality.

By incorporating these modifications, the BFS algorithm can be enhanced to handle larger game boards and
more complex games efficiently while still providing optimal solutions.
REFERENCES:

https://www.simplilearn.com/tutorials/data-structure-tutorial/bfs-algorithm

https://en.wikipedia.org/wiki/Tic-tac-toe

https://www.geeksforgeeks.org/implementation-of-tic-tac-toe-game/

https://www.educba.com/bfs-algorithm/

https://techindetail.com/breadth-first-traversal/

https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/

SOURCE CODE:

 https://github.com/YoussefMohamedHazo/Tic-tac-toe/blob/main/Tic-Tac-Toe.py

PRESENTATION:

 https://docs.google.com/presentation/d/1ISDUFXlx9Jn5WEdQfWYWUU23VPQ3JUCT/edit#slide=id.p1

You might also like