Menu

Artificial Intelligence Using Python [ Lab Programs ]


Write a Program to implement Tic-Tac-Toe game using Python.

SOURCE CODE :

 # Tuple to store winning positions.
win_positions = (
    (0, 1, 2), (3, 4, 5), (6, 7, 8),
    (0, 3, 6), (1, 4, 7), (2, 5, 8),
    (0, 4, 8), (2, 4, 6)
)
 
def game(player):
    # diplay current mesh
    print("\n", " | ".join(mesh[:3]))
    print("---+---+---")
    print("", " | ".join(mesh[3:6]))
    print("---+---+---")
    print("", " | ".join(mesh[6:]))
 
    # Loop until player valid input cell number.
    while True:
        try:
            ch = int(input(f"Enter player {player}'s choice : "))
            if str(ch) not in mesh:
                raise ValueError
            mesh[ch-1] = player
            break
        except ValueError:
            print("Invalid position number.")
 
    # Return winning positions if player wins, else None.
    for wp in win_positions:
        if all(mesh[pos] == player for pos in wp):
            return wp
    return None

player1 = "X"
player2 = "O"
player = player1
mesh = list("123456789")
 
for i in range(9):
	won = game(player)
	if won:
		print("\n", " | ".join(mesh[:3]))
		print("---+---+---")
		print("", " | ".join(mesh[3:6]))
		print("---+---+---")
		print("", " | ".join(mesh[6:]))
		print(f"*** Player {player} won! ***")
		break
	player = player1 if player == player2 else player2
else:
    # 9 moves without a win is a draw.
    print("Game ends in a draw.")

OUTPUT :

Sample Output: 
 1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9
Enter player X's choice : 5

 1 | 2 | 3
---+---+---
 4 | X | 6
---+---+---
 7 | 8 | 9
Enter player O's choice : 3

 1 | 2 | O
---+---+---
 4 | X | 6
---+---+---
 7 | 8 | 9
Enter player X's choice : 1

 X | 2 | O
---+---+---
 4 | X | 6
---+---+---
 7 | 8 | 9
Enter player O's choice : 6

 X | 2 | O
---+---+---
 4 | X | O
---+---+---
 7 | 8 | 9
Enter player X's choice : 9

 X | 2 | O
---+---+---
 4 | X | O
---+---+---
 7 | 8 | X
*** Player X won! ***

Related Content :

Artificial Intelligence Using Python

   Write a Program to Implement the following using Python

1) Breadth First Search View Solution

2) Depth First Search View Solution

3) Tic-Tac-Toe game View Solution

4) 8-Puzzle problem View Solution

5) Water-Jug problem View Solution

6) Travelling Salesman Problem View Solution

7) Tower of Hanoi View Solution

8) Monkey Banana Problem View Solution

9) Alpha-Beta Pruning View Solution

10) 8-Queens Problem View Solution