1

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]))
Joseph Budin
1,3701 gold badge14 silver badges33 bronze badges
asked Oct 15, 2019 at 12:16
1
  • {i , j} is an unordered set. You probably want a tuple, (i , j). Unless 2048 is symmetrical, I don't know. Commented Oct 15, 2019 at 12:21

1 Answer 1

2

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.

answered Oct 15, 2019 at 12:27
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Gonna look at it home

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.