Skip to content

Instantly share code, notes, and snippets.

@talitore
Created October 28, 2015 14:54
Show Gist options
  • Save talitore/78800448fdf3faab6af8 to your computer and use it in GitHub Desktop.
Save talitore/78800448fdf3faab6af8 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# Filename: tictactoe.py
import sys
import fnmatch
import random
def _start():
global picindex
picindex=1
_intro0()
_pic()
_intro1()
_again()
def _intro0():
global t
global spaces
spaces=[1,2,3,4,5,6,7,8,9]
t=1
print(" Let's play Tic-Tac-Toe!")
def _pic():
global spaces
print(' _____________________________\n \
| | | |\n \
| | | |\n \
| ', spaces[0], ' | ', spaces[1], ' | ', spaces[2], ' |\n \
| | | |\n \
|_________|_________|_________|\n \
| | | |\n \
| | | |\n \
| ', spaces[3], ' | ', spaces[4], ' | ', spaces[5], ' |\n \
| | | |\n \
|_________|_________|_________|\n \
| | | |\n \
| | | |\n \
| ', spaces[6], ' | ', spaces[7], ' | ', spaces[8], ' |\n \
| | | |\n \
|_________|_________|_________|')
def _intro1():
try:
first=0
players=int(input('''
How many players?
1 or 2
Choice: '''))
if players == 1:
_ai()
return
if players == 2:
_first()
return
else:
_intro1()
except TypeError:
print("That isn't a number silly...")
_intro1()
except ValueError:
print("That isn't a number silly...")
_intro1()
except KeyboardInterrupt:
_again()
sys.exit()
def _first():
global first
global piece
global next
try:
first=int(input('''
Who will go first?
X - 1
O - 2
Choice: '''))
print('\n')
except TypeError:
print("That isn't a number silly...")
_first()
except ValueError:
print("That isn't a number silly...")
_first()
except KeyboardInterrupt:
_again()
sys.exit()
if first < 3 and first > 0:
piece='X'
next='O'
if first==2:
piece='O'
next='X'
_play()
else:
print('Pick again!')
_first()
def _play():
global piece
global next
global spaces
global pick
global win
global t
global picindex
try:
_pic()
print(' Turn ', t)
print(' ', piece,'pick your spot!')
pick=int(input(' Choice: '))
if int(pick) > 9 or int(pick) < 1:
print('Choose 1-9 please!')
_play()
if pick in spaces:
spaces[pick-1]=piece
piece, next = next, piece
t += 1
_win()
if t == 10:
print('Stalemate!')
_again()
_play()
else:
print('That spot is taken. Try another.')
_play()
except TypeError:
print("That isn't a location...")
_play()
except ValueError:
print("That isn't a location...")
_play()
except KeyboardInterrupt:
_again()
sys.exit()
def _win():
global next
global win
global spaces
win=[str(spaces[0])+str(spaces[1])+str(spaces[2]),str(spaces[3])+str(spaces[4])+str(spaces[5]),str(spaces[6])+str(spaces[7])+str(spaces[8]),str(spaces[0])+str(spaces[3])+str(spaces[6]),str(spaces[1])+str(spaces[7])+str(spaces[4]),str(spaces[2])+str(spaces[5])+str(spaces[8]),str(spaces[0])+str(spaces[4])+str(spaces[8]),str(spaces[6])+str(spaces[4])+str(spaces[2])]
if win.__contains__('XXX')or win.__contains__('OOO'):
print(' Congrats!', next,'wins!')
_pic()
_again()
if t == 10:
print('Stalemate!')
_pic()
_again()
def _again():
global again
global againstr
try:
again=input(' Play again? ')
againstr=[again.lower()]
if againstr==['y'] or againstr==['yes']:
_start()
if againstr==['n'] or againstr==['no']:
sys.exit()
else:
print('Y or N')
_again()
except TypeError:
print("That isn't a location...")
_again()
except ValueError:
print("That isn't a location...")
_again()
except KeyboardInterrupt:
_again()
sys.exit()
def _ai():
global piece
global next
global turn
try:
ai=int(input('''
Who will go first?
Player - 1
AI - 2
Choice: '''))
if ai<3 and ai>0:
ai2=int(input(" Will you be X (1) or O (2)? "))
if ai2<3 and ai>0:
if ai2==1: # Player X
if ai==1: # Player first
piece='X'
next='O'
turn='X'
if ai==2: # AI first
piece='O'
next='X'
turn='X'
else: # Player O
if ai==1: # Player first
piece='O'
next='X'
turn='O'
if ai==2: # AI first
piece='X'
next='O'
turn='O'
else:
_ai()
else:
_ai()
except TypeError:
print("X (1) or O (2) ...")
_ai()
except ValueError:
print("X (1) or O (2) ...")
_ai()
except KeyboardInterrupt:
_again()
sys.exit()
_aiplay()
def _aiplay():
global piece, n, next, t, turn, win, move, int, rand, spaces, line, full
win=[str(spaces[0])+str(spaces[1])+str(spaces[2]),str(spaces[3])+str(spaces[4])+str(spaces[5]),str(spaces[6])+str(spaces[7])+str(spaces[8]),str(spaces[0])+str(spaces[3])+str(spaces[6]),str(spaces[1])+str(spaces[7])+str(spaces[4]),str(spaces[2])+str(spaces[5])+str(spaces[8]),str(spaces[0])+str(spaces[4])+str(spaces[8]),str(spaces[6])+str(spaces[4])+str(spaces[2])]
full=0
try:
_pic()
print(' Turn ', t)
print(' ', piece,'pick your spot!')
if turn==next:
print(' AI choosing...')
if spaces.__contains__(5):
print(' AI chooses: 5!')
spaces[4]=piece
t += 1
piece, next = next, piece
turn=piece
_win()
_aiplay()
n=_find(win,piece+piece+'*') # Search spaces to block
n=_find(win,next+next+'*') # Search spaces to win
if n!=None:
line=move[n]
_linecheck()
_win()
if full==1:
piece, next = next, piece
turn=piece
_aiplay()
n=_find(win,piece+'*'+piece) # Search spaces to block
n=_find(win,next+'*'+next) # Search spaces to win
if n!=None:
line=move[n]
_linecheck()
_win()
if full==1:
piece, next = next, piece
turn=piece
_aiplay()
n=_find(win,'*'+piece+piece) # Search spaces to block
n=_find(win,'*'+next+next) # Search spaces to win
if n!=None:
line=move[n]
_linecheck()
_win()
if full==1:
piece, next = next, piece
turn=piece
_aiplay()
if full==0:
_random()
spaces[rand-1]=piece
print(' AI chooses: ', rand, '!')
t += 1
piece, next = next, piece
turn=piece
_win()
_aiplay()
else: # Players turn start
pick=int(input(' Choice: '))
if int(pick) > 9 or int(pick) < 1:
print('Choose 1-9 please!')
_aiplay()
if pick in spaces:
spaces[pick-1]=piece
piece, next = next, piece
turn=next
t += 1
_win()
_aiplay()
else:
print('That spot is taken. Try another.')
_aiplay() # Players turn end
_aiplay()
except TypeError:
print("That isn't a location...")
_aiplay()
except ValueError:
print("That isn't a location...")
_aiplay()
except KeyboardInterrupt:
_again()
def _find(seq, pattern):
pattern = pattern.lower()
for i, n in enumerate(seq):
if fnmatch.fnmatch(n.lower(), pattern):
return i
return -1
def _index(seq, pattern):
result = _find(seq, pattern)
if result == -1:
raise ValueError
return result
def _contains(seq, pattern):
return _find(seq, pattern) != -1
def _random():
global rand
randindex=0
rand=[]
while randindex !=8:
try:
int(spaces[randindex])
rand.append(spaces[randindex])
randindex += 1
except ValueError:
randindex += 1
rand=random.choice(rand)
def _linecheck():
global spaces, t, turn, piece, next, line, full
if spaces[line[2]]!='X' and spaces[line[2]]!='O':
spaces[line[2]]=piece
print(' AI chooses: ', line[2]+1, '!')
t += 1
full=1
if full!=1:
if spaces[line[1]]!='X' and spaces[line[1]]!='O':
spaces[line[1]]=piece
print(' AI chooses: ', line[1]+1, '!')
t += 1
full=1
if full!=1:
if spaces[line[0]]!='X' and spaces[line[0]]!='O':
spaces[line[0]]=piece
print(' AI chooses: ', line[0]+1, '!')
t += 1
full=1
win=0
move=[(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,7,4), (2,5,8), (0,4,8), (2,4,6)]
_start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment