0

Hello :) I am currently trying to transition into python from c++ and java and am working on a small project that helps determine the state of a tic-tac-toe board.

I am currently trying to create the board itself and save whatever the user inputs into the console onto a 2D vector of size n x n (I determine this in a previous method)

I was testing out my code and when I input "xxxoooxxx" as the board, I keep receiving this as the output:

[['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']]

rather than:

[['x', 'x', 'x'], ['o', 'o', 'o'], ['x', 'x', 'x']]

I am able to properly iterate through the nested loops, but I am only having difficulty when it comes to updating the values in that 2D array.

Here is the code for the current method I am working on:

def create_board(self, board_str):
    str_to_chars = list(board_str)

    # 2D Board Vector
    rows, cols = (int(self.board_side_size), int(self.board_side_size))
    board = [[0 for x in range(rows)] for y in range(cols)]

    # Input is properly saved
    for row_index, row in enumerate(board):
        for column_index, column in enumerate(row):
            for char in str_to_chars:
                if char == 'x' or char == 'o':
                    board[row_index][column_index] = char
                else:
                    board[row_index][column_index] = ''
    print(board)
Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25
c-ort-n12
  • 3
  • 1
  • Does this answer your question? [Alternative way to split a list into groups of n](https://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n) – Buddy Bob May 25 '21 at 03:18

1 Answers1

0

You need to turn your string into an iterator so you can pull one at a time. Right now, your code is processing ALL 9 CHARACTERS for each square, so every square gets the last character in the list.

def create_board(self, board_str):
    str_to_chars = iter(board_str)

    # 2D Board Vector
    rows, cols = (int(self.board_side_size), int(self.board_side_size))
    board = [[0 for x in range(rows)] for y in range(cols)]

    # Input is properly saved
    for row_index, row in enumerate(board):
        for column_index, column in enumerate(row):
            char = next(str_to_chars)
            if char in 'xo':
                board[row_index][column_index] = char
            else:
                board[row_index][column_index] = ''
    print(board)

or:

def create_board(self, board_str):
    str_to_chars = iter(board_str)

    # 2D Board Vector
    rows, cols = (int(self.board_side_size), int(self.board_side_size))
    board = []

    # Input is properly saved
    for _ in range(rows):
        xrow = []
        for _ in range(cols):
            char = next(str_to_chars)
            if char in 'xo':
                xrow.append( char )
            else:
                xrow.append( '' )
        board.append( xrow )
    print(board)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30