0% found this document useful (0 votes)
182 views11 pages

Tic Tac Toe Game in Python Code

This project report outlines the development of a Tic Tac Toe game using Python, designed for two players with a text-based interface. The program validates user inputs, manages turns, and determines game outcomes while providing an engaging experience for beginners in programming. It can be further enhanced with features like a graphical user interface or AI opponent.

Uploaded by

ophi55566
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)
182 views11 pages

Tic Tac Toe Game in Python Code

This project report outlines the development of a Tic Tac Toe game using Python, designed for two players with a text-based interface. The program validates user inputs, manages turns, and determines game outcomes while providing an engaging experience for beginners in programming. It can be further enhanced with features like a graphical user interface or AI opponent.

Uploaded by

ophi55566
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

A

PROJECT REPORT
ON
“TIC TAC TOE GAME USING PYTHON”

SUBMITTED BY
Mst. Mahajan Atharva Vasant (145)
Under The Guidance Of
MR. [Link]

Department Of Computer Technology

Sanjivani Rural Education Society’s


SANJIVANI K.B.P. POLYTECHNIC
KOPARGAON – 423603, Dist- Ahmednagar

2024-2025

1
Sanjivani Rural Education Society’s
SANJIVANI K.B.P. POLYTECHNIC
Department of Computer Technology

SUBMITTED BY
Mst. Mahajan Atharva Vasant(145)

Under our supervision and guidance for partial fulfilment of the requirement for
DIPLOMA IN COMPUTER TECHNOLOGY affiliated to
Maharashtra State Board of Technical Education, Mumbai
For academic year
2024-2025

Subject Teacher HOD


[Link] [Link]

2
ACKNOWLEDGEMENT

We would take this opportunity to express our sincere thanks and


gratitude to our Project Guide [Link] Department of
Computer Technology, Sanjivani [Link], Kopargaon.
For his vital guidance and support in completing this project. Lots of
thanks to the Head of Computer technology Department Mr. G.N.
Jorvekar for providing us with the best support we ever had. We
like to express our sincere gratitude to Mr. A. R. Mirikar, Principal,
Sanjivani K. B. P. Polytechnic, Kopargaon for providing a great
platform to complete the project within the scheduled time. Last but
not the least; we would like to say thanks to our family and friends
for their never-ending love, help, and support in so many ways
through all this time. A big thanks to all who have willingly helped
us out with their ability.

Mst. Mahajan Atharva Vasant(145)

3
Table of Contents

[Link] Content [Link]

1. 5
ABSTRACT

2. INTRODUCTION 6

3. CODE 7-8

4. OUTPUT 9

5. CONCLUSION 10

6. REFERENCE 11

4
ABSTRACT
This Python program is designed to automate the classic two-player Tic Tac Toe
game using a structured, text-based interface. The core functionality of the
program revolves around checking valid moves, alternating player turns, and
determining game outcomes based on predefined win conditions. The program
utilizes a 3x3 grid and maps user input to board positions, ensuring data validity
by restricting entries to numeric values between 1 and 9 and preventing duplicate
or invalid moves. The game logic dynamically updates the board and evaluates
winning combinations across rows, columns, and diagonals after each turn. Upon
completion, the result is clearly presented, indicating whether a player has won
or if the game ended in a draw. This program enhances interactivity, minimizes
gameplay errors, and serves as a valuable tool for beginners learning Python
through game development. It can be further extended to include features such as
a graphical user interface (GUI), AI opponent, or score tracking for multiple
rounds.

5
INTRODUCTION

This Python program serves as a comprehensive implementation of the classic


Tic Tac Toe game, designed to provide an engaging and interactive experience
for two players. The game features a structured 3x3 grid layout, allowing
players to alternate turns and place their respective marks (X or O) on the board
until a win or draw condition is met. The program ensures smooth gameplay by
validating user inputs and restricting moves to valid, unoccupied positions,
thereby preventing accidental overwrites or out-of-range selections.

Players interact with the game by selecting numbered positions from 1 to 9,


which correspond to the grid blocks. The program maps these numbers to
appropriate board coordinates, enhancing ease of use and minimizing the
learning curve for new users. If a player enters an invalid input—such as a
number outside the 1–9 range, a non-numeric value, or an already occupied
block—the program prompts the user to try again, improving reliability and user
experience.

Throughout the game, the program continuously updates and displays the
current state of the board, enabling both players to track progress in real time.
After each move, the game logic checks for a winning combination by
evaluating rows, columns, and diagonals. If a winning condition is detected, the
program announces the winner and concludes the match. In cases where all nine
blocks are filled without a winner, the program declares a draw. This real-time
evaluation ensures accurate and fair results with every round.

The Tic Tac Toe program is particularly useful for beginners in Python
programming, educators, and anyone interested in building logical thinking
through interactive applications. It simplifies the complexities of game design
by demonstrating core programming concepts such as input handling,
conditionals, loops, and list manipulation. The program can also be extended or
customized with additional features, such as a graphical user interface (GUI), an
AI opponent, or score tracking across multiple rounds. Overall, this Python-
based game is a fun yet practical tool that introduces foundational programming
skills in an engaging and user-friendly format

6
CODE

def print_board(board):
for i in range(3):
print(" | ".join(board[i]))
if i < 2:
print("-" * 5)

def check_winner(board, player):


for i in range(3):
if all([cell == player for cell in board[i]]): # Rows
return True
if all([board[j][i] == player for j in range(3)]): # Columns
return True
if all([board[i][i] == player for i in range(3)]): # Diagonal
return True
if all([board[i][2 - i] == player for i in range(3)]): # Anti-diagonal
return True
return False

def is_full(board):
return all(cell != " " for row in board for cell in row)

def get_position(choice):
mapping = {
1: (2, 0), 2: (2, 1), 3: (2, 2),
4: (1, 0), 5: (1, 1), 6: (1, 2),
7: (0, 0), 8: (0, 1), 9: (0, 2),

7
}
return [Link](choice, (-1, -1))

def main():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"

while True:
print_board(board)
try:
choice = int(input(f"Player {current_player}, choose a position (1-9): "))
except ValueError:
print("Please enter a number from 1 to 9.")
continue

row, col = get_position(choice)


if row == -1 or board[row][col] != " ":
print("Invalid move. Try again.")
continue

board[row][col] = current_player

if check_winner(board, current_player):
print_board(board)
print(f" Player {current_player} wins!")
break
elif is_full(board):
print_board(board)
print("It's a tie!")
break

8
current_player = "O" if current_player == "X" else "X"
if __name__ == "__main__":
main()

OUTPUT

9
CONCLUSION
This Python program efficiently automates the classic two-player Tic Tac Toe
game using a simple text-based interface. It ensures valid user inputs, enforces
game rules, and dynamically updates the game board with each turn. The
program includes essential logic for detecting winning conditions, handling
invalid moves, and declaring outcomes such as wins or ties, ensuring a fair and
engaging gameplay experience.

By eliminating manual setup and tracking, the program enhances user


interaction and reduces the potential for errors during play. Its clean structure
and interactive design make it ideal for beginners learning programming
concepts such as conditionals, loops, functions, and basic data structures.

Overall, this program offers a well-structured and reliable implementation of


Tic Tac Toe, providing both entertainment and educational value. It can be
further extended to include a graphical user interface (GUI), AI opponent, score
tracking, or multiplayer support. With its clarity and functionality, this program
serves as a strong foundational project for learning and teaching core
programming skills.

10
REFERENCE
Python Documentation – The official Python documentation provides
comprehensive details on functions, lists, loops, and user input handling that
form the foundation of this game.
• Python Official Documentation
Conditional Statements in Python – The game's logic for checking wins,
handling turns, and validating moves relies heavily on if-elif-else structures.
• Python If-Else Statements
Handling User Input and Exceptions – Ensuring that users enter valid moves
(numbers between 1 and 9) is achieved through input validation and exception
handling using try-except blocks.
• Python Try-Except for Error Handling
Working with Lists and 2D Arrays – The 3x3 game board is implemented
using nested lists (2D arrays), a core concept in Python for managing structured
data.
• Python Lists and Data Structures
Loops in Python – While and for loops are used to control game flow,
repeatedly update the board, and manage user turns until a winner is found or
the board is full.
• Python Loops (While and For)

11

Common questions

Powered by AI

The Tic Tac Toe program serves as an introductory project for learning conditional statements by using if-elif-else structures to manage game logic. It checks win conditions by evaluating rows, columns, and diagonals, handles turns by alternating between players, and validates moves to restrict them to valid entries. These conditional constructs demonstrate practical applications of control flow, aiding beginners in understanding decision-making processes within programming contexts .

The main programming concepts demonstrated by enforcing game rules in the Tic Tac Toe Python game include input validation, conditional logic, and data manipulation. Input validation ensures that players enter only valid moves, while conditional logic helps manage game flow, such as alternating turns and assessing winning or draw conditions. Data manipulation is exhibited through updating and displaying the board state, which involves iterating over nested lists to check and reflect player moves and outcomes. These concepts collectively compose the game's core functionality and ensure a smooth operation .

The Tic Tac Toe program is an engaging and practical tool for teaching core programming skills because it combines simplicity with instructive value by demonstrating essential programming concepts such as loops, conditionals, functions, and error-handling mechanisms. Its interactive nature keeps learners engaged through real-time feedback and clear objectives (winning the game), while the manageable complexity of its logic fosters a deeper understanding without overwhelming beginners. Furthermore, its capacity for extensions, such as adding a GUI or an AI opponent, provides pathways for advanced learning, making it both foundational and adaptable as an educational resource .

Potential extensions of the Tic Tac Toe program, such as adding a graphical user interface (GUI), developing an AI opponent, and implementing score tracking for multiple rounds, significantly enhance user experience. A GUI makes the game visually appealing and more intuitive, lowering the barrier for non-technical users. An AI opponent introduces an opportunity for single-player engagement with varying difficulty levels, catering to diverse user skills. Score tracking adds a competitive element, engaging players over extended sessions and making the game more interactive and enjoyable .

Error handling using try-except blocks enhances the reliability of the Tic Tac Toe program by allowing it to gracefully manage unexpected input errors without crashing. When players enter invalid inputs, such as non-numeric values or numbers outside the valid range, the try-except structure captures these exceptions and prompts users to retry. This mechanism ensures that the game continues running smoothly, maintaining a seamless user experience and preventing disruptions due to input errors .

Design choices such as using a simple text-based interface with numeric input (ranging from 1 to 9) that corresponds directly to the 3x3 grid positions, and real-time board updates, improve user interaction and minimize the learning curve. This mapping of inputs to board positions is intuitive and reduces confusion, allowing new users to quickly understand the game mechanics. The program’s error handling further aids user experience by providing clear prompts for invalid inputs, thereby assisting users in making correct decisions .

The Tic Tac Toe Python program is particularly valuable for beginners due to its demonstration of core programming concepts such as input handling, conditionals, loops, and list manipulation. It simplifies game design complexities by providing an interactive application that maps user input to a 3x3 grid, validates moves, checks for winning combinations using rows, columns, and diagonals, and handles game outcomes. Additionally, it uses try-except blocks for error handling, which is crucial in understanding user input validation and exception management .

The use of nested lists to represent the game board in the Tic Tac Toe program provides a clear and efficient structure for managing the 3x3 grid layout. Each sublist corresponds to a row on the game board, allowing for straightforward manipulation and access during gameplay. This data structure facilitates iteration for checking win conditions and drawing the board state, offering a scalable way to manage board dynamics. Additionally, it introduces beginners to 2D array concepts, critical for handling complex data arrangements in programming .

The program ensures fair play by validating user inputs and restricting moves to valid, unoccupied positions. It prevents accidental overwrites or out-of-range selections by checking whether user input is numeric, falls within the specified range of 1-9, and corresponds to an unoccupied block on the 3x3 grid. If invalid input is detected, the program prompts the user to try again, enhancing reliability and ensuring a fair gaming experience .

Functions in the Tic Tac Toe program, such as `print_board`, `check_winner`, `is_full`, and `get_position`, help maintain a clean structure by encapsulating specific tasks and logic within reusable blocks of code. `print_board` manages the display of the current state, `check_winner` assesses winning conditions across different patterns, `is_full` checks for a draw condition, and `get_position` translates user input into board coordinates. This approach reduces code duplication, improves readability, and isolates errors, making it easier to develop and extend the program .

You might also like