1

i am making a noughts and crosses game and i wan to define some positions. Here is what i did...

def build():
 box = [["","",""],["","",""],["","",""]]
def positions():
 tl = box[0][0]
 ml = box[0][1]
 rl = box[0][2]
 lm = box[1][0]
 mm = box[1][1]
 rm = box[1][2] 
 bl = box[2][0]
 bm = box[2][1]
 br = box[2][2]

is there a way to shorten this code down? i could not find anything else to optimize my time in writing a bunch of box[][] statements.

  • But why write those variables when you already have the array? – tdelaney Apr 06 '21 at 04:41
  • We might need to know what those position parameters (e.g. tl, ml, rl) for. How'd they be used? – Simon Apr 06 '21 at 04:42
  • 1
    You can try [tuple/list unpacking](https://stackoverflow.com/questions/34308337/unpack-list-to-variables). For clarity, try assigning `box = [["tl","ml","rl"],["lm","mn","rm"],["bl","bm","br"]]` and then `(tl, ml, rl), (lm, mm, rm), (bl, bm, br) = box` – metatoaster Apr 06 '21 at 04:49
  • Suppose you define `T, M, B = 0, 1, 2` and `L, R = 0, 1`, then you could address the components as, for instance, `box[T][L]` which is about as clear as `tl`. – tdelaney Apr 06 '21 at 04:50
  • `L, R` should be `0, 2` – Simon Apr 06 '21 at 04:51
  • @Simon - yes, and since there are two middles, maybe different names. – tdelaney Apr 06 '21 at 05:13

1 Answers1

1

You could initialize the cells in one fell swoop and then make box a function of them, e.g.

tl = tm = tr = ml = mm = mr = ll = lm = lr = ''
box = lambda : ((tl, tm, tr), (ml, mm, mr), (ll, lm, lr))
print(box())
# (('', '', ''), ('', '', ''), ('', '', ''))

box() now reflects any changes you make to the labelled cells

tl, mm = 'x', 'o'
print(box())
# (('x', '', ''), ('', 'o', ''), ('', '', ''))
Jamie Deith
  • 706
  • 2
  • 4