A very basic tic tac toe in tkinter. one game win, loose, or draw and the game ends.
#! /usr/bin/env python3 '''tkinter tic tac toe''' import tkinter as tk import random as rnd from tkinter import messagebox import os class Game: def __init__(self, parent): # Set the parent self.parent = parent self.x_win = [1, 1, 1] self.o_win = [2, 2, 2] self.grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] self.grid_cords = [ (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2) ] for i in range(3): for j in range(3): self.frame = tk.Label(self.parent, borderwidth=1, relief='solid', \ cursor='hand2', width=12,height=5) self.frame.grid(column=i, row=j) self.frame.bind('<Button-1>', self.player_pick) def do_entries(self, text,col,row, fg='red'): label = tk.Label(self.parent, fg=fg, text=text, font=('serif', 50)) label.grid(column=col, row=row) def player_pick(self, event): x_cord = event.x_root - self.parent.winfo_rootx() y_cord = event.y_root - self.parent.winfo_rooty() loc = self.parent.grid_location(x_cord, y_cord) try : self.do_entries('X',loc[0],loc[1]) self.grid_cords.remove(loc) self.grid[loc[1]][loc[0]] = 1 except ValueError as error: print('Nothing left to pick') pass # Ckeck if player wins if self.x_win in self.possibilities(): ask = messagebox.showinfo('Winner', 'You are the winner!') os.sys.exit() self.computer() if self.o_win in self.possibilities(): ask = messagebox.showinfo('Lost', 'Sorry, you lost.') os.sys.exit() def pick(self): choices = self.grid player_choices = [] for choice in choices: print(choice) print(player_choices) def computer(self): if self.grid_cords: try: loc = rnd.choice(self.grid_cords) self.grid_cords.remove(loc) self.do_entries('0', loc[0], loc[1], fg='blue') self.grid[loc[1]][loc[0]] = 2 except ValueError as error: print(error) else: ask = messagebox.showinfo('Tie Game', 'You and the computer tied.') os.sys.exit() def possibilities(self): # Columns col1 = [self.grid[0][0], self.grid[0][1], self.grid[0][2]] col2 = [self.grid[0][1], self.grid[1][1], self.grid[2][1]] col3 = [self.grid[0][2], self.grid[1][2], self.grid[2][2]] # Rows row1 = [self.grid[0][0], self.grid[1][0], self.grid[2][0]] row2 = [self.grid[1][0], self.grid[1][1], self.grid[1][2]] row3 = [self.grid[2][0], self.grid[2][1], self.grid[2][2]] # Diagonals diag1 = [self.grid[0][0], self.grid[1][1], self.grid[2][2]] diag2 = [self.grid[2][0], self.grid[1][1], self.grid[0][2]] wins = [col1, col2, col3, row1, row2, row3, diag1, diag2] return wins root = tk.Tk() root.title('Tic Tac Toe') root.resizable(width=False, height=False) Game(root) root.mainloop()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts