views:

67

answers:

2

Hi I've been coding a console version of Minesweeper just to learn some of the basics of Python. It uses a coordinate system that is recorded in a dictionary. Now, I have been able to implement it successfully but accessing or assigning a value to a specific coordinate key using variables for the "x,y" of the coordinate seems... clunky. There are two different ways that I've come up with but they don't seem very elegant when I have to use them so often.

for i in range(1, ROWS+1):
        for j in range(1, COLS+1):
            mine_field["%i,%i" % (i,j)] = 0

or

for i in range(1, ROWS+1):
        for j in range(1, COLS+1):
            mine_field[",".join([i, j])] = 0

It works well enough but it does start to look messy when assigning or swapping values. Is there a better way that this can be done?

Thanks in advance.

+1  A: 

If you make mine_field a list of lists, then you can use nicer syntax:

mine_field = [[0]*ROWS for i in range(COLS)]

mine_field[i][j] = 1
Ned Batchelder
That is a good point! I haven't tried to work with list of lists yet in Python so I think I will create a v2.0 and implement it to get some practice. Thanks!
Quark_Nova
+5  A: 

Why not simply use a tuple as the key?

for i in range(1, ROWS+1):
    for j in range(1, COLS+1):
        mine_field[(i, j)] = 0 # you don't even need the parentheses!

Using this method, you can use comma-separated indices like so:

d = {(1,2):3}
print d[1, 2] # will print 3

And BTW why are you using one-based indices?

AndiDog
Ah yes tuples are the perfect solution for my problem. Thanks. And the one-based indices are mostly for aesthetics when printed. 1,1 would be the first box in the first column essentially.
Quark_Nova
I often find it enough to handle the +1/-1 transformation when dealing with input/output and internally learn to use 0-based Python (C etc) way.
Tony Veijalainen
I second that. It's easier to use zero-based indices and only convert it when printing the coordinates.
AndiDog