Sem 1 Python Ass 2
Sem 1 Python Ass 2
SUBMITTED BY,
812024106045 - SUBA SUBRAMANYAN K
ANNA UNIVERSITY
CHENNAI
DECEMBER-2024
GE3151- PROBLEM SLOVING AND PYTHON PROGRAMMING
TOPIC : CRETE A TIC-TAC-TOE GAME USING PYTHON PROGRAM
SUBMITTED BY,
812024106045 - SUBA SUBRAMANYAN K
MARK SPILT UP
Comprehension of K2
the project
Project Execution K3
Degree of result K3
accuracy
Presentation K3
Project Report K3
compliance
Collaboration and K3
Teamwork
Total Marks
1 CO105.1 K2 5
2 CO105.2 K2 5
3 CO105.3 K3 13
4 CO105.4 K3 13
5 CO105.5 K3 2
6 CO105.6 K3 2
Total Marks 40
PAGE
SERIAL NUMBER
CONTENT
NUMBER
1 ABSTRACT 4
2 INTRODUCTION 7
3 PROJECT PLANNING 11
5 IMPLEMENTATION 24
7 PROGRAM 38
8 OUTPUT 42
9 FUTURE ENHANCEMENTS 43
10 CONCLUSION 44
11 REFERENCES 45
CHAPTER 01
Abstract
Tic-Tac-Toe, also known as Noughts and Crosses, is a simple yet strategic game that has been a staple
of recreational activities for decades. It is played on a 3x3 grid where two players take turns marking
cells with either an "X" or "O." The objective is to form a line of three identical markers horizontally,
vertically, or diagonally, while preventing the opponent from doing the same. Despite its simplicity,
Tic-Tac-Toe is a fascinating example of how basic game mechanics can demonstrate critical concepts
The project serves as an ideal introductory exercise for programming enthusiasts due to its logical
simplicity and manageable complexity. By creating a Python program for Tic-Tac-Toe, developers
learn key concepts such as loops, conditionals, data structures, and function-based programming.
Python, being an accessible yet powerful programming language, facilitates the implementation of
game logic and ensures an engaging experience for developers and users alike. This project
emphasizes modularity, readability, and efficiency, making it suitable for beginners while allowing
The implementation of this project is designed to simulate a two-player game where users can
alternate turns and input their moves via a terminal-based interface. The program ensures that user
inputs are validated, checking for invalid or already occupied cells, and updates the board accordingly.
After each move, the program evaluates the state of the game to determine whether a player has won,
the game has ended in a draw, or the gameplay should continue. The simplicity of the terminal
interface ensures that users can interact with the program seamlessly, while the underlying logic
From a technical perspective, the Tic-Tac-Toe program employs a 3x3 grid represented as a two-
dimensional list in Python. Each cell of the grid can be empty or marked with either "X" or "O." This
data structure is chosen for its intuitive representation of the game board and its efficiency in
indexing specific cells. Functions are used to encapsulate specific tasks such as printing the board,
validating moves, switching turns, checking for win conditions, and detecting draw scenarios. This
modular design not only simplifies the development process but also enhances the program's
The project also introduces fundamental algorithmic concepts. For instance, win detection is
achieved by systematically evaluating rows, columns, and diagonals for a uniform marker. This is
implemented using simple loops and conditionals, reinforcing the importance of iteration and logical
reasoning in programming. Moreover, the process of validating user input involves error checking
and exception handling, ensuring that the program can gracefully handle invalid inputs without
disrupting the gameplay. Such practices are crucial for building robust and user-friendly applications.
While this project focuses on a two-player mode, it lays the foundation for integrating AI to simulate
algorithm commonly employed in two-player turn-based games. By evaluating all possible moves and
their outcomes, the Minimax algorithm ensures that the AI plays optimally, either maximizing its
chances of winning or minimizing the player’s advantage. Although the current implementation does
not include AI, the modular structure of the program allows for easy integration of such advanced
The educational value of this project cannot be overstated. It provides a hands-on opportunity to
apply theoretical programming knowledge to a practical problem. For beginners, the project
introduces core concepts like input handling, loops, conditionals, and modular programming. For
more experienced developers, it offers a chance to explore optimization, debugging, and the potential
integration of AI. Furthermore, the simplicity of the game allows for immediate feedback, fostering
Python’s syntax is clean and easy to understand, making it ideal for beginners, while its rich
ecosystem of libraries and tools ensures scalability and versatility. The implementation of Tic-Tac-
Toe showcases Python's strengths in handling structured data, managing flow control, and building
provide ample resources for developers seeking to enhance or troubleshoot their programs.
The project also highlights the importance of user experience in software design. While the game is
implemented as a terminal-based application, significant effort is made to ensure that the interface
is intuitive and engaging. The board is displayed clearly after each move, and the program provides
informative messages to guide players through the game. Such attention to detail not only improves
INTRODUCTION
Tic-Tac-Toe, also known as Noughts and Crosses, is a simple yet engaging two-player game that has
been played for centuries across various cultures. It is typically played on a 3x3 grid where two
players, represented by symbols "X" and "O," take turns marking one empty cell at a time. The
objective is to align three of one’s symbols in a row, column, or diagonal while simultaneously
preventing the opponent from achieving the same. The game ends when a player wins by forming
The rules of Tic-Tac-Toe are easy to learn, which makes it an ideal game for people of all ages. Despite
its simplicity, the game introduces strategic thinking, as players must anticipate their opponent's
moves and plan their own accordingly. For this reason, it has been extensively used in educational
settings to teach critical thinking, logic, and problem-solving skills. In the realm of programming, Tic-
Tac-Toe serves as an excellent project for beginners, allowing them to understand fundamental
This means that all possible game states can be computed, making it possible to develop an artificial
intelligence (AI) player that plays the game perfectly. While this project focuses on a two-player mode
without AI, the potential for expanding the program makes it an exciting starting point for learning
The primary objective of this project is to develop a fully functional Tic-Tac-Toe game using Python,
implemented as a terminal-based application. The project is designed to be a learning tool that helps
beginners grasp essential programming concepts while providing an engaging gaming experience.
The project aims to create a robust and efficient game logic system that handles tasks such as
alternating player turns, validating moves, and detecting the end of the game. This includes ensuring
that the game correctly identifies winning scenarios, draws, and ongoing gameplay.
Despite being terminal-based, the program is designed to display the game board in a clear and
intuitive manner. The interface prompts players for input, validates their moves, and provides
By working on this project, developers will gain hands-on experience with Python features such as
loops, functions, lists, and conditionals. The program also emphasizes modularity, encouraging
A key objective is to implement the program in a modular fashion, breaking the game into smaller,
manageable functions. For example, separate functions will handle tasks like printing the board,
While the current project focuses on two-player mode, the design is flexible enough to accommodate
future features. These could include integrating AI using the Minimax algorithm or creating a
In summary, the primary goal of this project is to develop a simple yet efficient implementation of
Tic-Tac-Toe while fostering a deeper understanding of Python programming. The project’s scope
makes it suitable for learners who are just beginning their programming journey.
This project holds significant value from both an educational and technical perspective. While Tic-
Tac-Toe may appear simple at first glance, its implementation introduces a wide range of
1. Educational Value:
The Tic-Tac-Toe project provides an excellent learning opportunity for beginners. It offers hands-on
experience with essential programming elements such as loops, conditionals, and data structures.
Through the process of coding the game, learners gain insights into problem-solving, debugging, and
optimizing algorithms. The project also introduces the concept of modularity, teaching students to
handling invalid inputs or detecting a draw. These scenarios encourage learners to adopt an iterative
approach to development, testing, and refinement. As a result, they build confidence and develop the
Python is widely regarded as an ideal language for beginners due to its readability and simplicity.
This project showcases Python’s versatility in handling tasks like input validation, managing game
states, and displaying data in a user-friendly manner. By working on this project, developers gain a
Additionally, the project demonstrates how Python can be used to create interactive applications.
While many beginner projects focus on static output, this project involves real-time user interaction,
The significance of this project extends beyond its educational value. Tic-Tac-Toe is often used as a
testbed for developing AI algorithms, such as the Minimax algorithm. While this project does not
include AI, it lays the groundwork for such enhancements. Understanding the core logic of the game
is essential for implementing an AI opponent that can evaluate game states and make optimal
decisions.
Moreover, the project introduces key concepts in game development, such as state management, win
condition checking, and input handling. These skills are transferable to more complex games,
The simplicity of Tic-Tac-Toe ensures that the project is accessible to learners of all levels. Its familiar
gameplay makes it instantly engaging, while its manageable complexity ensures that developers can
complete the project within a reasonable timeframe. This balance of simplicity and challenge makes
it an ideal choice for introducing programming concepts in a fun and interactive way.
The modular design of the project ensures that it is easy to understand, modify, and expand. For
example, the program can be adapted to include features like different grid sizes, multiple difficulty
levels, or even networked multiplayer functionality. This flexibility makes the project a valuable
CHAPTER 03
Project Planning
Effective project planning is crucial for ensuring a successful implementation of the Tic-Tac-Toe game
using Python. This section outlines the detailed requirements, the tools and technologies used, and
Functional Requirements Functional requirements define the core features and behavior of the Tic-
Tac-Toe game.
These include:
1. Game Board:
3. Move Validation:
Player inputs must correspond to valid grid positions (e.g., rows and columns within the grid).
Moves to already occupied cells should be disallowed, and players must be prompted to retry.
4. Win Detection:
The program should identify when a player has aligned three symbols in a row, column, or diagonal.
A winning message must display when a player wins, and the game ends.
5. Draw Detection:
If all cells are filled without a winner, the game should announce a draw and terminate.
6. User-Friendly Interface:
Display the game board after each move, with clear visuals and updated state.
Non-Functional Requirements
1. Efficiency:
The program should handle inputs and game state checks efficiently, with minimal delay.
2. Scalability:
While the initial implementation is for a 3x3 grid, the design should allow easy adaptation to larger
3. Reliability:
The program must handle edge cases, such as invalid inputs, gracefully without crashing.
4. Maintainability:
Code should be modular and well-documented for easy updates and debugging.
Programming Language
Python:
Python is chosen for its simplicity and readability, making it an ideal language for beginners and
small-scale projects like Tic-Tac-Toe. Its dynamic typing and built-in libraries simplify the
development process.
Development Environment
IDE/Code Editor:
Visual Studio Code (VSCode): A lightweight, feature-rich code editor with support for Python
extensions.
Alternatives: PyCharm, Sublime Text, or any text editor compatible with Python.
Standard Library:
The project relies on Python's built-in features such as lists for the game board and control flow
structures for logic implementation. No external libraries are required for this version.
Version Control
Git:
Using Git ensures version control, allowing the developer to track changes and revert to previous
states if necessary. GitHub can be used for project collaboration and backup.
Testing Tools
Manual Testing:
The game will be tested by simulating various scenarios manually. Automated testing is unnecessary
The development process follows an iterative approach, focusing on incremental progress and
continuous testing. The project is divided into four phases: planning, design, implementation, and
testing. Below is the detailed timeline and methodology for each phase:
1. Objective Definition:
2. Requirement Gathering:
Choose a 2D list to represent the 3x3 grid for simplicity and intuitive handling of the game board.3.
Modular Structure:
Plan how the board and prompts will appear in the terminal.
Display the game board and relevant messages after each move.
4. Integration:
Combine all functions into a main game loop that governs the flow of the game.
1. Manual Testing:
Test the program with different scenarios, including edge cases (e.g., invalid inputs, consecutive wins,
full board).
2. Bug Fixing:
3. Final Review:
Verify that the program meets all requirements and functions as intended.
Estimated Timeline
Development Methodology:
The project follows the Iterative Development Methodology, where features are developed and tested
in small increments. This approach ensures that issues are identified early and resolved promptly,
reducing the likelihood of major errors at the end of the project. Each module (e.g., input handling,
win detection) is independently developed and integrated into the main program.
CHAPTER 04
The design phase of the Tic-Tac-Toe project is critical to ensuring a seamless and engaging user
experience. This section outlines the detailed development of the game, focusing on the logic, user
Game logic design forms the backbone of the Tic-Tac-Toe program, ensuring the game operates as
intended. The logic encompasses all rules, player interactions, and game states required for smooth
gameplay.
The game board is implemented as a 3x3 grid using a two-dimensional Python list. Each element of
the list represents a cell on the board, initialized with placeholders (e.g., empty strings or numbers)
Example:
board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
2. Player Turns:
The game alternates between two players, "X" and "O." A variable, such as current_player, tracks
whose turn it is. After each move, this variable switches between "X" and "O."
3. Move Validation:
The program ensures that players enter valid moves corresponding to unoccupied cells. If an invalid
move is detected (e.g., a non-existent cell or an already filled one), the program prompts the player
to retry.
4. Win Conditions:
The game checks for three consecutive identical symbols (horizontally, vertically, or diagonally)
after each turn. The conditions are evaluated by iterating through rows, columns, and diagonals. For
example:
Check rows:
return True
5. Draw Detection:
A draw occurs when all cells are filled, and no player has won. The program counts the filled cells
The game is controlled through a loop that alternates player turns, checks for win/draw conditions,
and terminates when one is satisfied. The main loop ensures the game continues uninterrupted
The game interface is designed to be simple and intuitive, ensuring users can interact seamlessly
with the program. While the interface is text-based in this project, it emphasizes clarity and
functionality.
Board Display:
The game board is dynamically updated and displayed after each move. For example:
def display_board(board):
print(" | ".join(row))
print("-" * 9)
This creates a clear, visually distinct representation of the game state, allowing players to easily
Player Prompts
1. Input Prompts:
Players are prompted to enter their moves in terms of cell numbers. Example:
print(f"Player {current_player}, enter your move (1-9):")
2. Error Messages:
If a player enters an invalid move, the program clearly communicates the error and requests a valid
input.
Feedback Mechanisms
After every move, the program provides feedback on the game state:
"Player X wins!"
"It's a draw!"
Error Handling:
Invalid inputs, such as non-numeric or out-of-range values, are gracefully handled with clear
messages.
Once the game concludes, the program displays the final board state and a message indicating the
outcome. Example:
if winner:
A flowchart visually represents the game logic, providing a clear understanding of the decision-
making process.
Flowchart Steps
1. Start Game:
Initialize the game board and set the current player to "X."
2. Display Board:
3. Player Input:
4. Validate Input:
5. Update Board:
Evaluate rows, columns, and diagonals for three consecutive identical symbols.
8. Switch Turns:
9. Repeat Steps:
Display the final game board and announce the result (winner or draw).
Decision Nodes: Used for move validation, win detection, and draw conditions.
Process Nodes: Represent tasks such as updating the board, displaying the board, and switching
turns.
The flowchart visually simplifies the process, ensuring clarity for developers.
CHAPTER 05
Implementation
The implementation phase of the Tic-Tac-Toe game using Python involves translating the design
into executable code. This section details the data structures used, a breakdown of functionalities,
an optional AI implementation using the Minimax algorithm, and the challenges encountered
Efficient data structures are essential for managing the game's logic and user interactions. Below
The game board is represented as a 2D list. Each sub-list corresponds to a row in the grid, and
Example:
Advantages:
Players are represented as simple string variables ("X" and "O"), which alternate during gameplay.
Example:
current_player = "X"
Counters are used to track the total number of moves, facilitating draw detection when the board is
full.
Example:
move_count = 0
For advanced AI implementations, a dictionary can map board states to their corresponding
The program is modular, with each function serving a distinct purpose to simplify implementation
1. Game Initialization
This function initializes the game board and sets the current player.
This function updates and prints the board after each move.
Code Example:
def display_board(board):
print(" | ".join(row))
print("-" * 9)
The program prompts the current player to select a cell and validates the input.
Code Example:
valid = False
for i in range(3):
for j in range(3):
if board[i][j] == move:
board[i][j] = player
valid = True
return
A function evaluates rows, columns, and diagonals for three identical symbols.
Code Example:
def check_winner(board):
return row[0]
return board[0][col]
return board[1][1]
return None
5. Checking Draws
If no winner is detected and all cells are filled, the game ends in a draw.
Code Example:
def check_draw(board):
return False
return True
6. Game Loop
A loop controls the game flow, alternating turns, checking for wins/draws, and ending when a
condition is met.
Code Example:
def play_game():
while True:
display_board(board)
player_move(board, current_player)
if check_winner(board):
display_board(board)
break
if check_draw(board):
display_board(board)
print("It's a draw!")
break
For single-player mode, AI can be implemented using the Minimax algorithm to make optimal
decisions.
Objective: Minimax recursively evaluates all possible moves to maximize the AI's chances of
Scoring:
+1: AI wins.
0: Draw.
Minimax Function
winner = check_winner(board)
if winner == "O":
return 1
if winner == "X":
return -1
if check_draw(board):
return 0
if is_maximizing:
best_score = -float('inf')
for i in range(3):
for j in range(3):
if board[i][j].isdigit():
board[i][j] = "O"
board[i][j] = str(3 * i + j + 1)
else:
best_score = float('inf')
for i in range(3):
for j in range(3):
if board[i][j].isdigit():
board[i][j] = "X"
board[i][j] = str(3 * i + j + 1)
return best_score
AI Move Selection
def ai_move(board):
best_score = -float('inf')
best_move = None
for i in range(3):
for j in range(3):
if board[i][j].isdigit():
board[i][j] = "O"
board[i][j] = str(3 * i + j + 1)
best_score = score
best_move = (i, j)
if best_move:
board[best_move[0]][best_move[1]] = "O"
Solution: Implement input validation and error handling to reject invalid moves and prompt the
player again.
Challenge 2: AI Optimization
Problem: The Minimax algorithm can be computationally expensive for larger grids.
Solution: Use memoization to store previously evaluated board states, reducing redundant
calculations.
Challenge 3: User Interface Clarity
Problem: Displaying the board in a clear and user-friendly manner was challenging in a text-based
environment.
Solution: Carefully format the board output using loops and string manipulation to ensure
readability.
Problem: Rare cases, such as consecutive wins or draw detection glitches, caused unexpected
behavior.
Solution: Rigorously test the program with all possible game scenarios and refine the logic.
CHAPTER 06
CHAPTER 07
PROGRAM
import random
# Initial game state
board = [" ", " ", " ",
" ", " ", " ",
" ", " ", " "]
currentPlayer = "X"
winner = None
gameRunning = True
# Display the game board
def printBoard(board):
print(board[0] + " | " + board[1] + " | " + board[2])
print("---------")
print(board[3] + " | " + board[4] + " | " + board[5])
print("---------")
print(board[6] + " | " + board[7] + " | " + board[8])
# Player move input with validation
def playerInput(board):
while True:
try:
inp = int(input("Select a spot (1-9): "))
if 1 <= inp <= 9:
if board[inp - 1] == " ":
board[inp - 1] = currentPlayer
break
else:
print("Oops! That spot is already taken.")
else:
print("Invalid input. Choose a number between 1 and 9.")
except ValueError:
print("Invalid input. Please enter a valid number.")
# Check for horizontal win
def checkHorizontal(board):
global winner
for i in range(0, 7, 3):
if board[i] == board[i + 1] == board[i + 2] and board[i] != " ":
winner = board[i]
return True
return False
# Check for vertical win
def checkVertical(board):
global winner
for i in range(3):
if board[i] == board[i + 3] == board[i + 6] and board[i] != " ":
winner = board[i]
return True
return False
# Check for diagonal win
def checkDiagonal(board):
global winner
if board[0] == board[4] == board[8] and board[0] != " ":
winner = board[0]
return True
elif board[2] == board[4] == board[6] and board[2] != " ":
winner = board[2]
return True
return False
# Check if there's a winner
def checkIfWin(board):
global gameRunning
if checkHorizontal(board) or checkVertical(board) or checkDiagonal(board):
printBoard(board)
print(f"The winner is {winner}!")
gameRunning = False
# Check for tie
def checkIfTie(board):
global gameRunning
if " " not in board and winner is None:
printBoard(board)
print("It's a tie!")
gameRunning = False
# Switch player
def switchPlayer():
global currentPlayer
currentPlayer = "O" if currentPlayer == "X" else "X"
# Computer's move
def computer(board):
while currentPlayer == "O":
position = random.randint(0, 8)
if board[position] == " ":
board[position] = "O"
switchPlayer()
# Main game loop
while gameRunning:
printBoard(board)
playerInput(board)
checkIfWin(board)
checkIfTie(board)
if gameRunning:
switchPlayer()
computer(board)
checkIfWin(board)
checkIfTie(board)
CHAPTER 08
OUTPUT
CHAPTER 09
Future enhancement
While the Tic-Tac-Toe game is functional and performs well, there are several potential
improvements and future enhancements that could make the game more engaging and robust.
1. Improved AI with Alpha-Beta Pruning: Currently, the AI uses the Minimax algorithm, which can
be further optimized using Alpha-Beta Pruning. This technique reduces the number of nodes
evaluated in the game tree, resulting in faster decision-making and improving the game's
performance.
2. GUI Implementation: A graphical user interface (GUI) could be introduced using libraries like
Tkinter or Pygame. This would make the game more visually appealing and user-friendly, as
3. Multiplayer Online Mode: Adding an online multiplayer mode would allow players to compete
with friends or others over the internet, providing a more dynamic gaming experience.
4. Difficulty Levels for AI: Implementing multiple difficulty levels for the AI would cater to different
skill levels. Beginners could play against an easier AI, while experienced players could face a more
challenging opponent.
5. Board Customization: Offering a customizable board size (e.g., 4x4 or 5x5 grids) could add more
variety to the gameplay, providing players with more strategic options and complexity.
These enhancements would improve both the functionality and user experience, making the game
Conclusion
The implementation of the Tic-Tac-Toe game in Python successfully demonstrates core concepts of
game development, including logic design, user interaction, and the integration of artificial
intelligence (AI). This project provided an opportunity to explore key programming techniques such
as recursion, board state management, and AI algorithm optimization using the Minimax algorithm.
The game offers both two-player functionality and a single-player mode with an AI opponent,
Through thorough testing, the program was verified to handle all major game scenarios, including
win conditions, draws, and invalid inputs. The AI’s performance was optimized with the Minimax
algorithm, allowing it to make decisions based on the best possible outcomes. Debugging and
optimization efforts improved the efficiency of the code, especially in handling edge cases and
In terms of future enhancements, there is significant potential to improve the game. Implementing
Alpha-Beta Pruning could optimize the AI's performance, while introducing a graphical user
interface (GUI) would make the game more interactive and visually appealing. Additionally, the
addition of multiplayer capabilities and customizable board sizes would further enrich the
gameplay.
Overall, this Tic-Tac-Toe game project serves as a foundation for further exploration into game
development and AI. It provides a solid understanding of how to structure a game, implement
decision-making algorithms, and optimize the code for a smoother user experience. The project’s
simplicity also makes it an ideal starting point for exploring more complex game development
Reference
A beginner-friendly guide to Python programming, covering basic concepts that were useful in
the development of the Tic-Tac-Toe game. This book provides a strong foundation in Python
This comprehensive book provides an in-depth understanding of Python programming and object-
oriented design, which are essential for building well-structured applications like Tic-Tac-Toe.
A key text on artificial intelligence that includes detailed discussions on search algorithms,
Russell, Stuart, and Peter Norvig. Artificial Intelligence: A Modern Approach. 3rd ed., Pearson, 2010.
libraries, and functions used throughout the development of the Tic-Tac-Toe game.
A useful online article that explains the Minimax algorithm in depth, which was central to the AI
algorithm-in-game-theory-set-1-introduction/.
This website offers tutorials and resources on game development in Python, providing valuable
7. Stack Overflow
A popular online forum where developers can ask questions and find solutions to coding problems.
Many questions related to Python and game development, including Tic-Tac-Toe, have been
answered here.