TypeError: 'int' object is not iterable...2D array

608 views Asked by At

I'm trying to set a class property of a cell contained in the multidimensional array Board.grid. I get the following error message:

  File "newbs1.py", line 133, in get_and_set_board_item
    self.grid[x, y].set_cell(value, secondary)
  File "newbs1.py", line 129, in __getitem__
    return self.grid[x][y]
  File "newbs1.py", line 128, in __getitem__
    x, y = tup
  TypeError: 'int' object is not iterable

The idea of having the x and y entered how they are came from a post by someone else, it fixed their problem but it hasn't worked for me.

class Board(object):
    def __init__(self):
        self.grid = []
        self.width = 10
        self.height = 10

    def __getitem__(self, tup):
        x, y = tup
        return self.grid[x][y]

    def get_and_set_board_item(self, x, y, value, secondary):
        print (x, y, value, secondary)
        self.grid[(x, y)].set_cell(value, secondary)


class Cell():
    def __init__(self):
        self.is_ship = False
        self.is_hidden = False
        self.ship_symbol = ""

    def set_cell(self, value, secondary):
        if secondary == None:
            self.is_hidden = value
        else:
            self.is_ship = value
            self.ship_symbol = secondary
1

There are 1 answers

0
Ephellon Grey On

I'm not sure how the rest of your code looks, but on line:133, self.grid[(x, y)].set_cell(value, secondary), it doesn't look like the tuple (x, y) is a Cell type.

Maybe try:

class Board(object):
    def __init__(self):
        self.grid = []
        self.width = 10
        self.height = 10

    def __getitem__(self, tup):
        x, y = tup
        return self.grid[x][y]

    def get_and_set_board_item(self, x, y, value, secondary):
        print (x, y, value, secondary)
        # add this line #
        self.grid[x][y] = Cell() # set this to a cell type
        # ************* #
        self.grid[x][y].set_cell(value, secondary)


class Cell():
    def __init__(self):
        self.is_ship = False
        self.is_hidden = False
        self.ship_symbol = ""

    def set_cell(self, value, secondary):
        if secondary == None:
            self.is_hidden = value
        else:
            self.is_ship = value
            self.ship_symbol = secondary