Jon Hrovat Jon Hrovat - 26 days ago 9
Python Question

Python: storing object in 2d array and calling its method

I'm trying my hand at making a chess app. Code below:

#file containing pieces classes
class Piece(object):`

name = "piece"
value = 0
grid_name = "____"


class Pawn(Piece):

# Rules for pawns.
#If first move, then can move forward two spaces

name = "Pawn"
value = 1
grid_name = "_PN_"
first_move = True


#Main file
from Piece import *



class GameBoard:

pieces = []
grid = [][]

def __init__(self):

self.grid[1][0] = self.pieces.append(Pawn())



currentBoard = GameBoard()


I want to call the value variable for the object located at grid[1][0]

It would look something like:

print currentBoard.grid[1][0].value


This code doesn't work which tells me I'm missing something regarding the scope of the objects and variables. Is this something that is possible in Python?

Answer

Rewriting your code so that it simply runs as a single file:

#file containing pieces classes
class Piece(object):
     name = "piece"
     value = 0
     grid_name = "____"


class Pawn(Piece):
    # Rules for pawns.
    #If first move, then can move forward two spaces

    name = "Pawn"
    value = 1
    grid_name = "_PN_"
    first_move = True

class GameBoard:

   pieces = []
   grid = [[],[]]

   def __init__(self):

      self.grid[0][1] = self.pieces.append(Pawn())



currentBoard = GameBoard()

There are a few things that need to be corrected. For one, the variables defined in Piece, Pawn and GameBoard are not defined under the __init__() method. This means that these variables will be shared by all instances of the class.

Example:

>>> pawn1 = Pawn()  # Make two Pawns
>>> pawn2 = Pawn()
>>> print pawn1.first_move, pawn2.first_move
True, True
>>> pawn1.first_move = False  # Change the first pawns attribute
>>> print pawn1.first_move, pawn2.first_move # But both change
False, False

To avoid this, define your class attributes under the method __init__() for all three of your classes.

Example:

class Pawn(Piece):
    # Rules for pawns.
    #If first move, then can move forward two spaces
    def __init__(self):
        self.name = "Pawn"
        self.value = 1
        self.grid_name = "_PN_"
        self.first_move = True

Next, your variable grid is not properly defined in python. If you wanted a list with two empty lists you could do the following

grid = [[], []]

But an easy way to make an 8x8 structure of empty lists would be to do the following

grid = [[[] for i in xrange(8)] for j in xrange(8)]
Comments