[Tutor] Generating dynamic output

Charles Karl Becker charleshbecker at gmail.com
Fri Dec 2 00:30:14 CET 2011


Hi everyone,

My CS mentor (not school credit, just a friend helping me with some
blindspots and pointers, etc) has been having me write, and then
extend, a Tic Tac Toe game.  Currently I'm working on dynamically
creating the board/output with varying sizes so the user can define
the size of the board.

The following code works, I'm using Python 3.2 on Windows 7, however
I'm sure there is some way to optimize this that I'm just missing
(particularly on the line generations, some way to not need to remove
the last character).  I probably over-commented, but wanted to make it
easier to parse.

So the main thing I'm looking for are pointers on how I could
optimize/refactor this, and any resources on this and how to 'think'
more in the right way for this type of thing.  Also, please let me
know what's good about it :P  As you can see my understanding of list
comprehensions has grown a lot since my initial post here.  I'm
sending this as plain text after the sig, if any indenting is lost
please let me know and I can send the file

Thanks!
Charles

def build_line(part):
    ''' dynamically builds and returns the static lines for use in the board '''
    line = [part for x in range(board_size)]
    line = ''.join(line)
    line = line[:-1]
    return line

# defines the board size
board_size = 5

# these pieces are used in creating the two static lines
part1 = '   |'
part2 = '---|'

# this creates a list of the line #s which will be dynamic (if 0 is the first)
dynamic_list = [x for x in range(board_size)[1:board_size*board_size:4]]

# generates the array used for controlling the board spaces/taken locations
master = [[str(x+1), 0] for x in range(board_size**2)]

# this section builds the two static lines
line1 = build_line(part1)
line2 = build_line(part2)

# these are used for loop/flow control
b = 0 # this is used to tell which line needs to be printed
c = 0 # this controls the slicing to tell the board where to start 'temp_row'
# this generates the board on the fly
for row in range(board_size*4-1):
    if(b == 0 or b == 2):
        print(line1)
    elif(b == 3):
        print(line2)
    elif(b == 1):
        # since these rows are dynamic they are called 'temp_row'
        # and are reset each time a new one is made
        temp_row = ''
        for cell in master[c:c+board_size]:
            if(int(cell[0]) >= 100):
                temp_row += '{0}|'.format(cell[0])
            if(int(cell[0]) >= 10):
                temp_row += '{0} |'.format(cell[0])
            else:
                temp_row += ' {0} |'.format(cell[0])
        c += board_size # this is how this variable determines where
to start next time
        temp_row = temp_row[:-1] # need to get rid of extra '|' at end of line
        print(temp_row)
    # this is just some loop/flow control
    b += 1
    if(b == 4):
        b = 0


More information about the Tutor mailing list