Due date: April 29, 2024
Python Program about Tic Tac Toe
Purpose: We are going to create a Python program
to play tic tac toe.
Complete the assignment below:
You will need to create the following 3 files:
PX_TicTacToe_lastname.py (Actual python program)
PX_TicTacToe_lastname.png (Screen shot of program running in the IDE)
PX_TicTacToe_lastname.mp4 (Video)
(Explaining the program and running the program)
Be sure to turn it into google classroom.
/* Instructions:
* Copy the python program code below.
*/
Python program for a two-player Tic-Tac-Toe game.
It uses the console for input and output,
letting two players take turns to
mark Xs and Os on a 3x3 grid.
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
win_conditions = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]],
[board[0][0], board[1][1], board[2][2]],
[board[2][0], board[1][1], board[0][2]]
]
if [player, player, player] in win_conditions:
return True
return False
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
player_turn = "X"
moves_count = 0
while True:
print(f"Player {player_turn}'s turn.")
print_board(board)
try:
row = int(input("Enter the row number (1-3): ")) - 1
col = int(input("Enter the column number (1-3): ")) - 1
if board[row][col] == " ":
board[row][col] = player_turn
moves_count += 1
else:
print("This cell is already taken. Try another one.")
continue
except (ValueError, IndexError):
print("Invalid input. Please enter numbers between 1 and 3.")
continue
if check_winner(board, player_turn):
print_board(board)
print(f"Player {player_turn} wins!")
break
elif moves_count == 9:
print_board(board)
print("It's a draw!")
break
player_turn = "O" if player_turn == "X" else "X"
if __name__ == "__main__":
tic_tac_toe()
How to Use This Program:
Start the Game: Run the script in your Python environment. The game starts automatically.
Player Turns: The program asks each player (X and O) to enter the row and column where they want to place their mark. Rows and columns are numbered from 1 to 3.
End of Game: The game ends when one player has three of their marks in a row (horizontally, vertically, or diagonally) or when all nine squares are filled, resulting in a draw.
Players need to enter row and column numbers each turn, and the board is updated and displayed after each move. The game detects and announces a winner or a draw and then terminates.