0

I am currently working on a connect4 game and so coded a class for the game. When I instantiate 2 class/game, whatever I do to the first class is copied on the second. How can I have two distinct instance? Here is the code (I work on jupyter notebook):

import numpy as np

class Connect4:
    def __init__(self, board = np.zeros((6, 7))):
        if(board.shape != (6, 7)):
            raise Exception("board is invalid")
        if(np.sum(board) == 0):
            self.player = 1
        elif(np.sum(board) == 1):
            self.player = -1
        else:
            raise Exception("board is invalid")
        self.board = board

    def play(self, move):
        if(move not in self.getLegalActions()):
            return True, -self.player
        for row in range(6):

            if(self.board[row][move] == 0):
                self.board[row][move] = self.player
                self.player = -self.player
                return self.checkWin()

            else:
                continue

        return(self.checkWin())


game1 = Connect4()
game2 = Connect4()

game1 == game2 returns false but when I play on game1 and then check game2's board, they are always the same.

The bug goes away when I call instead

game1 = Connect4(np.zeros((6, 7)))
game2 = Connect4(np.zeros((6, 7)))

but it does not make sense to me why just calling game1 = Connect4() doesn't work. If anyone knows what is the difference.

laheau
  • 1
  • Calling `game1` doesn't work because you are passing it in directly constructor method. – Sunderam Dubey Feb 27 '22 at 03:30
  • The issue, in case the answer above doesn't reveal it, is the use of a default argument. There is only ONE `np.zeros((6,7))` object created, when the class is defined. All instances will share that object. You need to do something like `def __init__(self, board=None):` / `if not board:` / `board = np.zeros((6,7))`. – Tim Roberts Feb 27 '22 at 04:13
  • And note that `if` and `return` statements in Python do NOT use an extra pair of parentheses, like you have here. That's a bad habit left over from C coding. – Tim Roberts Feb 27 '22 at 04:13

0 Answers0