Search code examples
pythonpython-3.xlisttic-tac-toe

Printing Tic Tac Toe game board?


I'm making a tic tac toe game in python and I have all of the actual game play functions working properly but I can't get the game board to print correctly.

game = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
for row in game:
  print('   |'*(len(game)-1)+'   ')
  for space in row:
    print(' '+space+' |',end='')
  print('\n'+'   |'*(len(game)-1)+'   ')
  if game.index(row) < len(game)-1:
    print('----'+('----'*(len(game)-2))+'---')

for some reason the row index isn't incrimenting unless there's a move in each row. When the game begins empty the output is:

   |   |   
   |   |   |
   |   |   
-----------
   |   |   
   |   |   |
   |   |   
-----------
   |   |   
   |   |   |
   |   |   
----------- 

There shouldn't be a line along the bottom but it goes away when there's a move in each row. I'm also trying to get rid of the ' |'in the middle of each space on the right. Any tips or suggestions would be greatly appreciated!


Solution

  • The problem seems to be that you are using the index method instead of something like enumerate. index returns the position of a given element in a list, whereas enumerate can be used to do more of what you want (see Accessing the index in 'for' loops?). When you use index(row), you are asking for the lowest index value at which the given row occurs. On a blank board, this always comes back as 0.

    Another way to get around this is to set a counter for the rows (as in the example below).

    As for the extra line on the character row, you can get around this by printing the row contents differently, as in the example below.

    cur = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
    
    # initialize a row counter
    rownumb = 0
    
    for row in cur:
        print(cur.index(row))
    
        # increment the row counter
        rownumb += 1
        print('   |'*(len(cur)-1)+'   ')
    
        # a different approach to printing the contents of each row
        print(' ' + row[0] + ' | ' + row[1] + ' | ' + row[2])
    
        print('   |'*(len(cur)-1)+'   ')
    
        # check the counter and don't print the line after the final row
        if rownumb < 3:
            print('----'+('----'*(len(cur)-2))+'---')