15,499,289 members
1.00/5 (1 vote)
See more:
I have to write a code for determining winner for my tic tac toe code. Can someone please help me doing it bc i have no idea how to...

below is the codes I have

What I have tried:

```def superscript(n):
out = ""
while(n>0):
v = n%10
if(v==1):
out = "\u00b9" + out
elif(v==2 or v==3):
out = chr(ord("\u00b0")+v) + out
else:
out = chr(ord("\u2070")+v) + out
n //= 10
return out

def printBoard(board):
for i in range(len(board)):
if(board[i] == ""):
print(superscript(i+1),end="")
else:
print(board[i],end="")

if(i%3<2):
print("",end="|")
elif(i<len(board)-1):
print("\n-+-+-")
else:
print()

def getRow(board, row):
return board[3*row:3*(row+1)]

def getCol(board, col):
return [board[col],board[col+3],board[col+6]]

def getDia(board, dia):
return [board[dia*2],board[4],board[2*(4-dia)]]

def getValidInput(board):
while(True):
user = input("Enter a position: ")
if(len(user)==1):
if("1"<=user and user<="9"):
t = int(user)-1
if(board[t]==""):
return t
else:
print("...that position has already been filled\n")
else:
print("...coordinates out of bounds\n")
else:
print("...invalid inputs\n")

#determine winner code

board = [""]*9
turn = True
count = 1
winner = ""
t = -1
decorator = t

while(True):
printBoard(board)
if(turn):
print("\nX's turn")
else:
print("\nO's turn")

t = getValidInput(board)
if turn:
board[t] = "X"
else:
board[t] = "O"

#DETERMINE WINNER IF ANY, setting winner to the correct value.

#CHECK IF THERE WAS A WINNER

#CHECK IF TIE

print("\n\n")

count += 1
turn = not(turn)```
Posted
Updated 23-Jun-22 21:25pm

## Solution 1

You know, in order to check for a winner, you must check for full (that is having the same symbol) rows, columns or diagonals.
I give you an example (checking rows):
Python
```def check_row(board, row):

cntX = 0
cnt0 = 0
for i in range(row*3,row*3+3):
if board[i]=="X":
cntX = cntX+1
elif board[i]=="O":
cnt0 = cnt0+1
else:
return ""

if cntX==3:
return "X"
else:
return "O"```

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 200 CPallini 40 merano99 30 Richard MacCutchan 30 Parth Vijay 20
 OriginalGriff 3,520 Richard MacCutchan 1,909 Richard Deeming 1,483 Graeme_Grant 1,391 CPallini 1,148

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900