Tic Tac Toe Program in Python shows errors when checking for diagonal wins

Question:

I’m making a tic tac toe in python and when creating a diagonal check, I keep getting the wrong results. In my script, I have a 2D list with all of the values on the board:

filled = [['n','n','n'],
          ['n','n','n'],
          ['n','n','n']]

This changes whenever the user enters values to add an X or O, for example:

filled= [['X','X','n'],
         ['n','O','O'],
         ['n','n','n']]

My horizontal and vertical checks work fine but my diagonal check gives me false wins whenever I run it. Here’s the function:

def Dcheck(filled):
 global win
 global winner
 global turn
 dxcount = docount = 0

 # Negative Diagonal (1,5,9)
 x = 0
 for row in filled:
      if row[x] == 'X':
           dxcount+=1
      elif row[x] == 'O':
           docount +=1
      x+=1
           
 if dxcount == 3:
      win,winner,turn = True,'X',0
 elif docount == 3:
      win,winner,turn = True,'O',0
         
 dxcount = docount = 0

 # Positive Diagonal (3,5,7)
 x = 2 
 for row in filled:
      if row[x] == 'X':
           dxcount+= 1
      elif row[x] == 'O':
           docount += 1
      x -= 1

 if dxcount == 3:
      win,winner,turn = True,'X',0
 elif docount == 3:
      win,winner,turn = True,'O',0
           

 return [win,winner,turn,dxcount,docount]

Now, whenever I play a game like this:

filled = [['X','O','O'],
          ['X','X','n'],
          ['n','n','n']]

X gets a win, even when it’s not supposed to. Same goes if you invert the board to the right side. I still don’t understand what I’m doing wrong. Thanks in advance for the help!

Edit: My Github repo if you want the whole script (it’s tic_tac_toe.py): https://github.com/DarthKitten2130/PyGames.git

Asked By: DarthKitten

||

Answers:

I think the error stems from another function, Vcheck.

def Vcheck(filled):
     global win
     global winner
     global turn
     vxcount = vocount = 0
     for x in range(3):
          for row in filled:
               if row[x] == 'X':
                    vxcount+=1 # <--- is never reset
               elif row[x] == 'O':
                    vocount+=1
     if vxcount == 3:
          win,winner,turn = True,'X',0
     elif vocount == 3:
          win,winner,turn = True,'X',0 # <---- 'X' should be 'O'

There you do not reset vxcount while looping (line 92, following). So you actually count the number of ‘x’ in your game which is 3 in your example.
Also you want to have another look at line 101. There you checked the win condition for ‘O’ but put ‘X’ as a winner.

Answered By: Flow
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.