2

I'm trying to create a connect 4 class, but whenever I drop a letter/token, it updates the entire column. I can't figure out for the life of me why this is happening:

class ConnectFour():
def __init__(self, width, height):
    self.width = width
    self.height = height        
    self.board = [[0] * width] * height

def dropLetter(self, letter, col):
    count = self.height - 1
    while count > 0 and self.board[count][col] != 0:
        count -= 1
    print self.board[count][col] 
    self.board[count][col] = letter     
    print self.board

C = ConnectFour(4,4)
C.dropLetter('X', 0)

Then when I print self.board, every slot in the provided column is updating. Why is this happening?

TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

1 Answers1

4

Problem is here:

self.board = [[0] * width] * height

When you do so, self.board contains height references to the same row of [0]*width. Now you need to change it to

self.board = [[0]*width for _ in range(height)]
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74