0

I am new to Python, and I am working on a Tic Tac Toe game coded using OOP. After completing the tile, however, I cannot figure out how to determine the winner (or draw). Here is the code:

import tkinter as tk

root =tk.Tk()
root.title('Tic Tac Toe')
player = 'cross'

class Tile():
    def __init__(self):
        self.tile = tk.Button(
            root,
            font = ('Arial', 35),
            width=3,
            command = self.write
        )

    def write(self):
        global player
        if player == 'cross':
            self.tile.config(text = 'X', state = tk.DISABLED)
            player = 'circle'
        elif player == 'circle':
            self.tile.config(text = 'O', state = tk.DISABLED)
            player = 'cross'
        else:
            print('wrong var')
    def grid(self, row, column):
        self.tile.grid(row=row, column=column)


for row in range(0,3):
    for column in range(0,3):
        Tile().grid(row, column)

root.mainloop()

I wonder if I can assign a name to each of the tile objects, so that I can call them later and get the button text of each of them, hence compare them with the win conditions.

2
  • You need to apply simple logic here. Check for every possible win and loose situations. If no one wins and the board is full consider it draw. Commented Jul 2, 2021 at 7:35
  • I believe that this is the common solution to a tic tac toe program. But what if the game is more complicated? Say a tic tac toe played on a 5x5 board instead of a 3x3 board Commented Jul 2, 2021 at 9:22

1 Answer 1

1

If you change your setup to

tiles = []
for row in range(0,3):
    tiles.append([])
    for column in range(0,3):
        tiles[-1].append(Tile())
        tiles[-1][-1].grid(row, column)

you can access your tiles as tiles[row][column] at the end and get the text to compare against the win conditions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.