Python project
Class: XI-A
Project title:
x/o game
by: Bright Thomas and Aryan Srivatsav
Introduction:
This Python code implements a simple text-based totally Tic-Tac-Toe game.
Here's a breakdown of its common sense:
1. **Board Representation:**
- The sport board is represented as a 3x3 matrix initialized with empty spaces
(' ') the usage of a nested list.
2. **Printing the Board:**
- The `print_board` feature is chargeable for showing the current nation of
the Tic-Tac-Toe board.
Three. **Checking for a Winner:**
- The `check_winner` characteristic examines rows, columns, and diagonals
to decide if a player has won.
- It iterates via every row and column, checking if all factors are equal to the
cutting-edge participant ('X' or 'O').
- It additionally assessments each diagonals for a winning combination.
Four. **Checking for a Draw:**
- The `is_board_full` function checks if there aren't any empty areas left on
the board, indicating a draw.
5. **Main Game Loop (`tic_tac_toe` characteristic):**
- The sport starts with an empty board, and 'X' is the starting player.
- It enters a loop wherein the board is displayed, and the modern player is
induced to go into a row and column.
- If the chosen cell is empty, the player's symbol is placed in that mobile.
Otherwise, the participant is brought on to strive once more.
- After each move, the code checks for a winner or a draw. If neither is
executed, it switches to the following participant.
6. **End of Game:**
- If a participant wins, the winning board is displayed, and the winner is
announced.
- If the board is complete and there's no winner, the sport proclaims a draw.
7. **Main Block:**
- The recreation is commenced by calling `tic_tac_toe` if the script is
administered directly (now not imported as a module).
Python code:
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
# Check rows, columns, and diagonals for a win
for i in range(3):
if all(board[i][j] == player for j in range(3)) or \
all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or \
all(board[i][2 - i] == player for i in range(3)):
return True
return False
def is_board_full(board):
return all(board[i][j] != ' ' for i in range(3) for j in range(3))
def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'
while True:
print_board(board)
row = int(input("Enter the row (0, 1, or 2): "))
col = int(input("Enter the column (0, 1, or 2): "))
if board[row][col] == ' ':
board[row][col] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
elif is_board_full(board):
print_board(board)
print("It's a draw!")
break
current_player = 'O' if current_player == 'X' else 'X'
else:
print("Cell already taken. Try again.")
if __name__ == "__main__":
tic_tac_toe()
Output :