0

I am trying to create a program for the game Connect Four where the board can be anysize. The user is prompted for the number of rows and numbers of columns which through some code creates a 2d list of 0 open spot. So for a 3 column by 4 row board

blankBoard = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]]

I am trying to create a function that inputs, the list, and column to drop the play piece into, represented by an X... so for example if you chose column 3, the updated board list will appear as such

blankBoard = [[0,0,0],[0,0,0],[0,0,X],[0,0,0]]

My function is suppose to take the input for the column, and find the index inside that column list which is the last one which is blank. My problem is maining deleting and replacing that specific index with out changing all the lists.

def move(blankBoard, column):
    newBoard = blankBoard[:]
    col = column - 1  # The first column in connect four is 1, not 0
    index = -1
    i = 0
    while i < len(newBoard[col]):
        if newBoard[col][i] == 0:
            index = index + 1
        i = i + 1
    newBoard[col][index] = "X"   # This line of code I think is bad
    print(newBoard)
    return ""

with the following output...

newBoard = [[0,0,X],[0,0,X],[0,0,X],[0,0,X]]

but as I said I only want the X to be in the sublist denoted by "col" Why is it looping through all the columns (sublists) in the list if the code line to change the specifc index of the sublist is not in the while loop?

JoeStat1986
  • 79
  • 1
  • 5

1 Answers1

0

Can't you just loop through the reversed list and break after setting the first (after reversing, really the last) 0 to x?

a = [0,0,'x']
for i in reversed(range(len(a))):
  if a[i] == 0:
    a[i] = 'x'
    break
print a # will print [0, 'x', 'x']

[EDIT]

Running your code with a call to move with blankBoard as a parameter will give the expected result, not the behaviour you describe. If you, however, call move with [[0]*3]*4 as a parameter or [arr,arr,arr,arr] as a parameter (where arr = [0,0,0]), the repeating behaviour will occur. This is because in the last two examples, all the sublists are a reference to the same list.

See https://stackoverflow.com/a/240205/1458374

Community
  • 1
  • 1
EvenLisle
  • 4,672
  • 3
  • 24
  • 47
  • ... that may work. But Im more concerned with why my code does not work. I am going to have many similar type codes that involve looping through different sublists of a list and replacing specific indexes in specific sublists/ – JoeStat1986 Apr 23 '15 at 15:55