Advertisement
here2share

# Tk_Tic_Tac_Toe.py

May 12th, 2024
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. # Tk_Tic_Tac_Toe.py
  2.  
  3. from tkinter import *
  4. import math
  5. import random
  6.  
  7. root = Tk()
  8. root.title("Tk_Tic_Tac_Toe")
  9. root.geometry("+-10+0")
  10.  
  11. canvas_width_px = 197
  12. canvas_height_px = 197
  13.  
  14. canvas = {}
  15.  
  16. def button(i, j):
  17.     canvas[i,j] = Canvas(root, width=canvas_width_px, height=canvas_height_px, bg="white")
  18.     canvas[i,j].bind("<Button-1>", lambda event, row=i, col=j: click(row, col))
  19.     canvas[i,j].grid(row=i,column=j)
  20.    
  21. def reset(e=None):
  22.     global sss
  23.     sss = ''
  24.    
  25. def click(row, col):
  26.     global play
  27.     if '!' not in sss:
  28.         if p == 'X':
  29.             canvas[row, col].create_line(10, 10, canvas_width_px - 10, canvas_height_px - 10, width=7, fill=colour[p], capstyle='round')
  30.             canvas[row, col].create_line(canvas_width_px - 10, 10, 10, canvas_height_px - 10, width=7, fill=colour[p], capstyle='round')
  31.         else:
  32.             canvas[row, col].create_oval(10, 10, canvas_width_px - 10, canvas_height_px - 10, width=7, outline=colour[p])
  33.         canvas[row, col].unbind("<Button-1>")
  34.         play = str(row*3+col+1)
  35.        
  36. def turns():
  37.     lbl.config(text=p+"'s Turn - Click Here To Reset")
  38.  
  39. colour={'O':"deep sky blue",'X':"lawn green"}
  40.  
  41. lbl=Label(font=('arial',30))
  42. lbl.grid(row=3,column=0,columnspan=3,sticky='EW')
  43. lbl.bind("<Button-1>", reset)
  44.  
  45. Z_WIN_CHECK='123 456 789 147 258 369 159 357' ### for win checking
  46.  
  47. play = '?'
  48. sss = 'go'
  49.  
  50. while play.lower() != 'q':
  51.     p = 'O'
  52.     for i in range(3):
  53.         for j in range(3):
  54.             button(i, j)
  55.     turns()
  56.    
  57.     win_check = Z_WIN_CHECK
  58.     while sss:
  59.         if play in win_check:
  60.             win_check=win_check.replace(play, p)
  61.             if p*3 in win_check:
  62.                 sss = "Player '"+p+"' Won !!!"
  63.                 lbl.config(text=sss)
  64.             else:
  65.                 p = ('X' if p == 'O' else 'O')
  66.                 turns()
  67.             play = '?'         
  68.         root.update()
  69.     sss = 'go'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement