Skip to content

Instantly share code, notes, and snippets.

@0xpizza
Created December 5, 2020 00:34
Show Gist options
  • Select an option

  • Save 0xpizza/f2a79b4cb6e04ca3082e3531f3cd4083 to your computer and use it in GitHub Desktop.

Select an option

Save 0xpizza/f2a79b4cb6e04ca3082e3531f3cd4083 to your computer and use it in GitHub Desktop.
import itertools
import tkinter as tk
class Tile(tk.Label):
default = ' '
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.config(
borderwidth=2,
relief='solid',
font='courier 100 bold'
)
self.symbol = Tile.default
def clear(self):
self._symbol = None
self.config(text=' ')
@property
def symbol(self):
return self._symbol
@symbol.setter
def symbol(self, s):
self._symbol = s
self.config(text=s)
class TicTacToe(tk.Frame):
def __init__(self, master=None, **kwargs):
bheight = kwargs.pop('bheight', 3)
bwidth = kwargs.pop('bwidth', 3)
self.symbols = itertools.cycle(kwargs.pop('symbols', 'XO'))
super().__init__(master, **kwargs)
self.config(background='blue')
self.tiles = []
for row in range(bheight):
for col in range(bwidth):
t = Tile(self)
t.bind('<Button-1>', self.play_move)
t.grid(row=row, column=col)
self.tiles.append(t)
def play_move(self, event):
tile = event.widget
if tile.symbol != ' ':
self.error_tile(tile)
else:
tile.symbol = next(self.symbols)
#self.check_win(tile)
def check_win(self, tile):
info = tile.grid_info()
col = info['column']
row = info['row']
def error_tile(self, tile):
original_color = tile.config('background')[-1]
tile.config(background='red')
self.after(100, lambda: tile.config(background=original_color))
def main():
root = tk.Tk()
TicTacToe(root).pack()
root.mainloop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment