As a beginner I started to code a 2048 game. I made the matrix and filled it with 0's. Then I wanted to write a function which loops trough the whole matrix and find all the 0 values. Then save the coordinates of the 0 values and later replace them with 2 or 4 values. I made a random variable to choose beetween 2 or 4. The problem is, that i don't really know how to push the x and y coordinates of the 0 values to and array and then read them.
table = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
options = []
def saveOptions(i, j):
options.append([{i , j}])
return options
def optionsReaderandAdder(options):
if len(options) > 0:
spot = random.random(options)
r = random.randint(0, 1)
if r > 0.5:
table <-------- THIS IS THE LINE WHERE I WOULD LIKE TO CHANGE THE VALUE OF THE 0 TO 2 OR 4.
def optionsFinder():
for i in range(4):
for j in range(4):
if table[i][j] == 0:
saveOptions(i, j)
optionsReaderandAdder(options)
addNumber()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in table]))
You can iterate over the rows and columns of the table:
for row in table:
for element in row:
if element == 0:
# now what?
We don't know what the coordinate is.
Python has a useful function named enumerate
. We can iterate the same way as previously, but we also get the index, or position into the array.
zeroes = []
for i, row in enumerate(table):
for j, element in enumerate(row):
if element == 0:
zeroes.append((i, j))
We can then set the values, for example all to 2
:
for i, j in zeroes:
table[i][j] = 2
Your random code looks fine.