Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_tictactoe_str_replace.py
- # magic trick for less coding than the typical way --
- # layout[1]='123 456 789 147 258 369 159 357' ### for win checking
- # layout[z]=layout[z].replace(play,['.',p][z])
- from Tkinter import *
- import math
- root = Tk()
- root.title("Tk Tic-Tac-Toe")
- ww = 520
- hh = 520
- from time import sleep as x
- import os
- cls=lambda: os.system('cls')
- r=range
- def console(s=''):
- cls()
- t=t2
- if '!' in s:
- t=''
- mv="Player %s's Turn..."%p
- print(layout[0]+t.replace('@',mv)+s)
- def button(frame):
- b=Button(frame,padx=1,bg="lightyellow",width=3,text="",font=('arial',40,'bold'),relief="sunken",bd=3)
- return b
- def reset(e=None):
- global sss
- sss = ''
- def click(row,col):
- global play
- if '!' not in sss:
- b[row][col].config(text=p,state=DISABLED,disabledforeground=colour[p])
- play = str(row*3+col+1)
- colour={'O':"deep sky blue",'X':"lawn green"}
- lbl=Label(font=('arial',30))
- lbl.grid(row=3,column=0,columnspan=3,sticky='EW')
- lbl2=Label(text="Click Here To Reset",font=('arial',10))
- lbl2.grid(row=4,column=0,columnspan=3,sticky='EW')
- lbl.bind("<Button-1>", reset)
- lbl2.bind("<Button-1>", reset)
- play = '?'
- sss = 'go'
- while play.lower() != 'q':
- p='O'
- layout = {}
- b=[[],[],[]]
- for i in range(3):
- for j in range(3):
- b[i].append(button(root))
- b[i][j].config(command=lambda row=i,col=j:click(row,col))
- b[i][j].grid(row=i,column=j)
- lbl.config(text=p+"'s Turn")
- t2='''
- +++
- @
- '''
- layout[0]='''
- 1 | 2 | 3 | |
- ---+---+--- ---+---+---
- 4 | 5 | 6 | |
- ---+---+--- ---+---+---
- 7 | 8 | 9 | |
- '''
- layout[1]='123 456 789 147 258 369 159 357' ### for win checking
- console()
- while sss:
- if play in layout[1]:
- t=list(layout[0])
- t[layout[0].index(play)+15]=p # updates the right-side of console layout
- layout[0]=''.join(t)
- ### a minimalistic approach is using the replace method
- for z in (0,1):
- layout[z]=layout[z].replace(play,['.',p][z])
- if p*3 in layout[1]:
- sss = "Player "+p+" Won !!!"
- console("\n\t"+sss)
- elif layout[0].count('.') == 9:
- sss = "Tied Game!"
- console("\n\t"+sss)
- else:
- console()
- p = ('X' if p == 'O' else 'O')
- lbl.config(text=p+"'s Turn")
- play = '?'
- if sss != 'go':
- lbl.config(text=sss)
- root.update()
- play = '?'
- sss = 'go'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement