Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #To check whether the computer or Human has won"
- def check(l):
- #The z here is just a counter to see whether you have completed all the three squares
- z=0
- #List a are all the ways you can win
- a=[[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,6],[3,6,9],[1,5,9],[3,5,7]]
- for i in a:
- #The for loop extracts through the List a
- z=0
- for j in i:
- #This for loop extracts through i,which is an element of list a
- if j in l:
- z=z+1
- #If z is 3 it means that the person has completed all the squares
- if z==3:
- break
- if z==3:
- return(3)
- #This function shows the board currently
- def board(l1,l2):
- a=['-','-','-','-','-','-','-','-','-']
- #This for loop is to check where the computer and the human has placed their mark
- for i in range (1,10):
- #This if checks where the mark is and places it on the respective squares
- if i in l1:
- #This puts cross where the human has marked and knot for where the computer has marked in the respective list position
- a[i-1]="X"
- if i in l2:
- a[i-1]="O"
- print(a[0],a[1],a[2])
- print(a[3],a[4],a[5])
- print(a[6],a[7],a[8])
- import random
- print("The layout is ")
- print()
- print(" 1 2 3")
- print(" 4 5 6")
- print(" 7 8 9")
- #Here l is all the valid moves
- l=[1,2,3,4,5,6,7,8,9]
- l1=[]
- l2=[]
- for i in range (1,6):
- print("Your valid positions are ",l)
- while True:
- a=float(input("Enter where you would like to place the cross "))
- if a not in l:
- print("Wrong input,enter again")
- continue
- if a in l:
- break
- #Here the append function appends your move in list1/l1
- l1.append(int(a))
- print(l1)
- #Here the l.remove removes one of the valid position,which is a. a is the position chosen by you
- l.remove(a)
- #Calling the check function defined above
- y=check(l1)
- #As the check function returns 3 if all the 3 sqaures are marked
- if y==3:
- print("You win ")
- #Board is the function defined above
- board(l1,l2)
- break
- if i==5:
- break
- #random.choice chooses a random option from list L
- c=random.choice(l)
- #Here the l.remove removes one of the valid position,which is a. a is the position chosen by the computer
- l.remove(c)
- l2.append(c)
- print("I placed my knot in number ",c)
- board(l1,l2)
- y=check(l2)
- #As the check function returns 3 if all the 3 sqaures are marked
- if y==3:
- print("I win ")
- board(l1,l2)
- break
Add Comment
Please, Sign In to add comment