I'm writing a program for a basic "tic tac toe" game in which I want to print "match draws" when the variable "won" is returned as False at the end of game after exiting my for loop.
Although everything is working fine, it still won't print "match draws" at the end.
Please also suggest how to make it shorter or improve it, or how I could improve it. I'm just starting.
Below is the basic code:
import numpy
import random
board=numpy.array=["-","-","-"],["-","-","-"],["-","-","-"]
p1s="x"
p2s="o"
def place(symbol):
print (numpy.matrix(board))
while(1):
row=int(input("enter row"))
col=int(input("enter column"))
if (row>0 and row <4 and col>0 and col<4 and board[row-1][col-1]=="-"):
break
else:
print("please enter valid input")
board[row-1][col-1]=symbol
def won(symbol):
return check_rows(symbol) or check_columns(symbol) or check_diagonals(symbol)
def check_rows(symbol):
for r in range(3):
count=0
for c in range(3):
if board[r][c]==symbol:
count+=1
if (count==3):
print(numpy.matrix(board))
print(symbol,"won")
return True
return False
def check_columns(symbol):
for c in range(3):
count=0
for r in range(3):
if board[r][c]==symbol:
count+=1
if (count==3):
print(numpy.matrix(board))
print(symbol,"won")
return True
return False
def check_diagonals(symbol):
if (board[0][0] == board[1][1] and board[1][1]==board[2][2] and board[1][1]==symbol):
print(numpy.matrix(board))
print(symbol,"won")
return True
if (board[0][2] == board[1][1] and board[1][1]==board[2][0] and board[1][1]==symbol):
print(numpy.matrix(board))
print(symbol,"won")
return True
return False
def play():
turn=start+1
count=1
for count in range(8):
if turn%2==0:
print("count is",count)
count+=1
turn+=1
print("X turn")
place(p1s)
if won(p1s):
break
else:
print("count is",count)
count+=1
turn+=1
print("O turn")
place(p2s)
if won(p2s):
break
if (won==False):
print("match draws")
start=random.randint(1,100)
print(start)
if (start%2==0):
print("X turn")
place(p1s)
play()
else:
print("O turn")
place(p2s)
play()
won
is a function object, so you cannot simply compare it to a Boolean value and expect the comparison to be true.
You can instead use the for-else
construct to consider the game a draw if the loop doesn't break
from finding a player winning.
Change:
if (won==False):
print("match draws")
to:
else:
print("match draws")