[Python] Tic-tac-toe 03-01-2013, 10:43 AM
#1
Language : Pyhton 2.7
You can play with bot or against other player.
Positions:
Code:
import random
def draw(dict):
val=0
for i in range(3):
for j in range(3):
print dict.get(val,' '),
if 3-j!=1:
print'|',
val+=1
print('')
if 3-i!=1:
print('-'*9)
def check(loc):
if loc.get(0,' ')==loc.get(1,' ') and loc.get(1,' ')==loc.get(2,' ') and loc.get(0,' ')!=' ':
return loc[0]
elif loc.get(3,' ')==loc.get(4,' ') and loc.get(4,' ')==loc.get(5,' ') and loc.get(3,' ')!=' ':
return loc[3]
elif loc.get(6,' ')==loc.get(7,' ') and loc.get(7,' ')==loc.get(8,' ') and loc.get(6,' ')!=' ':
return loc[6]
elif loc.get(0,' ')==loc.get(3,' ') and loc.get(3,' ')==loc.get(6,' ') and loc.get(0,' ')!=' ':
return loc[0]
elif loc.get(1,' ')==loc.get(4,' ') and loc.get(4,' ')==loc.get(7,' ') and loc.get(1,' ')!=' ':
return loc[1]
elif loc.get(2,' ')==loc.get(5,' ') and loc.get(5,' ')==loc.get(8,' ') and loc.get(2,' ')!=' ':
return loc[2]
elif loc.get(0,' ')==loc.get(4,' ') and loc.get(4,' ')==loc.get(8,' ') and loc.get(0,' ')!=' ':
return loc[0]
elif loc.get(2,' ')==loc.get(4,' ') and loc.get(4,' ')==loc.get(6,' ') and loc.get(2,' ')!=' ':
return loc[2]
else:
return 'none'
def winner(loc):
if check(loc) != 'none':
print('')
print('Winner is ' +str(check(loc)))
return True
def first():
print('')
axe=int(raw_input('Enter your position x : '))
if axe in loc:
print('Oops!that position is not empty.')
return first()
loc[axe]='x'
print('')
draw(loc)
def second():
print('')
zero=int(raw_input('Enter your position 0: '))
if zero in loc:
print('Oops!that position is not empty.')
return second()
loc[zero]='o'
print('')
draw(loc)
def bot():
print('')
zero=random.choice(range(9))
print('Bot choosed :'+str(zero))
if zero in loc:
print('Oops!that position is not empty.')
return bot()
loc[zero]='o'
print('')
draw(loc)
loc={}
mode=raw_input('Enter game mode [c to play against computer | o to play with other] : ')
if mode=='o':
draw(loc)
while len(loc)!=9:
if winner(loc):
break
first()
if len(loc)==9:
if winner(loc):
break
else:
print('')
print('Draw')
break
if winner(loc):
break
second()
elif mode=='c':
draw(loc)
while len(loc)!=9:
if winner(loc):
break
first()
if len(loc)==9:
if winner(loc):
break
else:
print('')
print('Draw')
break
if winner(loc):
break
bot()
You can play with bot or against other player.
Positions:
![[Image: Untitled.png]](http://s24.postimage.org/ejtp2auxt/Untitled.png)
![[Image: fow57.jpg]](http://i.imgur.com/fow57.jpg)