November 21, 2019

Tic Tac Toe algorithm and source code in python

Tic Tac Toe algorithm and source code in python

After a short break, This the first program I wrote in python

n=3#int(input("Enter size of board! "))

def printbox(lst):
    for i in range(2*n+1):
        if i%2==0:
            for k in range(n):
                if k==0:
                    print('  ', end='')
                print('----  ', end='')
        else:
            for k in range(n+1):
                if k==n:
                    print(' |', end='')
                else:
                    pp = addcolor(lst[(i-1)/2,k])
                    print(' |',pp, end='')
        print('')

def addcolor(num):
    if num == 1:
        return '\033[0;37;41m '+str(num)+'\033[0m'
    elif num==2:
        return '\033[0;37;46m '+str(num)+'\033[0m'
    return num

import numpy as np
#strlst = '1,0,1,2,1,1,0,2,1'#input("give 9 numbers")
lst=np.zeros(9).reshape(3,3)

def iswinner(lst):
    printbox(lst)
    
    issame=True
    knum=0
    for i in range(3):
        if np.all(lst[i,:]==1) or np.all(lst[:,i]==1):
            return(1)
        elif np.all(lst[i,:]==2) or np.all(lst[:,i]==2):
            return 2
        if i==0:
            knum=lst[i,i]
        elif issame and knum!=lst[i,i]:
            issame=False
    if issame and knum!=0:
        return knum
    return 0

s=0
while s<9:
    strlst1 = input('your move i,j,number')
    i,j,knum=strlst1.split(',')
    if (s%2==0 and int(knum)==1) or (s%2==1 and int(knum)==2):
        lst[i,j]=knum
        iswin = iswinner(lst)
        if iswin == 1:
            print('1 is winner')
            break
        elif iswin==2:
            print('2 is winner')
            break
        else:
            print('no win')
        s+=1
    else:
        print('enter valid number')



paste code in 
and run





Developed by steffi thomas

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments