Asaaj
Asaaj

Reputation: 272

How to recursively create individually accessible objects

I am fairly new at Python and lack formal training. Everything I have learned has been through books and a few videos I have seen. So while I understand basic concepts, I still have trouble with some things many better coders may take for granted. So I need help with this.

I was working on a chess program, and while creating the pawns, I got to wondering how to create them all with one function but be able to access them separately later to change their individual positions. I can't make a string into a variable, like I hoped.

class Name(object):
    def __init__(self, posx, posy, posz):
        self.pos= (posz, posy, posz)
        box(pos=self.pos)

Then I can just create a bunch with positions from a list, but still access them all as separate objects.

Upvotes: 0

Views: 517

Answers (2)

Matthew Trevor
Matthew Trevor

Reputation: 14961

One way to make it easier on yourself is to not have the pieces worry about where they are, instead delegating that to a Board object:

import string

class Piece(object):
    def __init__(self, type, colour):
        self.type = type
        self.colour = colour
    def __str__(self):
        return 'Piece(%(type)s, %(colour)s)' % self.__dict__

class Board(dict):
    def __init__(self, width, height):
        self.update(
            dict(((x,y), None) 
                for x in string.ascii_lowercase[:width] # alphabetic axis 
                for y in xrange(1, height+1)            # numeric axis
            )
        )

    def setup(self, position_seq):
        for type, colour, position in position_seq:
            self[position] = Piece(type, colour)

initial_positions = [
    ('rook', 'W', ('a', 1)),
    ('knight', 'W', ('b', 1)),
    ('bishop', 'W', ('c', 1)),
    ('queen', 'W', ('d', 1)),
    ('king', 'W', ('e', 1)),
    ('pawn', 'W', ('a', 2)),
]

b = Board( 8,8 )
b.setup( initial_positions )
print b['a',1] # returns Piece(rook, W)

The setup method for the Board takes a list of tuples, with each containing the data needed to instantiate a new piece, as well as specifying where it should go on the board. No recursion necessary, just a simple loop passing data into a class.

Upvotes: 2

Antimony
Antimony

Reputation: 39451

How do you want to access them? If you want to access them by string key, then the simplest way is to put them in a dict. However I am not sure this is what you actually want to do. A more common practice would be to just put them in a list.

Upvotes: 0

Related Questions