0

I was trying to make chess playing algorithm that "bruteforces" possible options and choosing the best.

To do this, I wrote class, which represents board situation on board(showed the parts that used in bad code).

class Chess:
    def __init__(self):
        #Here is the board 2D array - enemy is downside.
        self.board = [[ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK], [PAWN for i in range(8)], [EMPTY for i in range(8)], [EMPTY for i in range(8)], [EMPTY for i in range(8)], [EMPTY for i in range(8)], [ENEMYPAWN for i in range(8)], [ENEMYROOK, ENEMYKNIGHT, ENEMYBISHOP, ENEMYKING, ENEMYQUEEN, ENEMYBISHOP, ENEMYKNIGHT, ENEMYROOK]]

    def WriteBoard(self):
        WriteBoard(self.board)

    def Moove(self, x1, y1, x2, y2):
        if x1 >= 8 or x1 < 0 or x2 >= 8 or x2 < 0 or y1 >= 8 or y1 < 0 or y2 >= 8 or y2 < 0:
            raise IndexError("Parameter is not correct.")
            return
        #WARNING: Not checking if moove correct.
        self.board[y2][x2] = self.board[y1][x1]
        self.board[y1][x1] = EMPTY

Where:

EMPTY = 0

PAWN = 2
ROOK = 17
KNIGHT = 10
BISHOP = 14
QUEEN = 45
KING = 60

ENEMYPAWN = -2
ENEMYROOK = -17
ENEMYKNIGHT = -10
ENEMYBISHOP = -14
ENEMYQUEEN = -45
ENEMYKING = -60

...Next part is function that returns possible moves getting Chess variable and x, y as parameters:

def PossibleMooves(chessBoard, x, y):
    possibleMooves = []
    target = chessBoard.board[y][x]
    if target == EMPTY:
        return possibleMooves
    helpVar = chessBoard

    if target == PAWN:
        try:
            if helpVar.board[y + 1][x] == EMPTY:
                helpVar.Moove(x, y, x, y + 1)
                possibleMooves += [res]
                index += 1
                helpVar = chessBoard
        except IndexError as e:
            ... #print(e)
    elif target == ROOK:
        ...
    ... #And so on...
    return possibleMooves

Please note that try...except statement helps to establish correctness of move(index like [y + 1][x] can not exist)

But the problem is:

Variable chessBoard changing together with helpVar, and variable that were given to function.

You can check it with this code:

chess = Chess()

print(chess.board[1][1])
results = PossibleMooves(chess, 1, 1)
print(chess.board[1][1])

Output should be:

2
2

But its:

2
0

Jenia
  • 374
  • 1
  • 4
  • 15

1 Answers1

1

helpVar = chessBoard means that every change you make to helpVar will be reflected in chessBoard. They point to the same object. If you want to avoid it - clone chessBoard and work with a copy.

See here about copy in python. (Look at deepcopy)

balderman
  • 22,927
  • 7
  • 34
  • 52