I'm creating a chess game within python. It contains 2 modules - one, called main.py, contains the setup of the game, and also controls user input. The other module, called chess.py, determines the valid moves that can be made each turn, and stores the current condition of the game. I am trying to determine the list of legal moves that can be made each turn. The list is empty for now, but as it is declared in the chess module, and executed in the main module, I run into a circular dependency when trying to call the function into the main module.
Here is the function written in the chess module:
def legalMoves(self):
moveList = []
print (self.startSquare)
pieceColour = self.board[self.startSquare[0]]
pieceType = self.board[self.startSquare[1]]
for row in range(8):
for col in range(8):
if pieceColour == 'w' and self.whiteTurn == True or pieceColour == 'b' and self.whiteTurn == False:
if pieceType == 'p':
self.pawnMoves()
self.board is a visualisation of the chess board as a 2-dimensional list. It is contained in its own class called chessboard, which is also in the chess module. Its purpose is to iterate through the list and, based on the characters in each index, draw the corresponding chess piece on each square.
class chessboard(
): #creates a chessboard visualised through a 2D list. This list will determine the positions and types of pieces on the board
def __init__(self):
self.board = [
['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'],
['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['--', '--', '--', '--', '--', '--', '--', '--'],
['wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp'],
['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR'],
]
The code that runs this function in main is:
legalMoves = chess.legalMoves(self)
However, when I run the program, I immediately run into this error:
NameError: name 'self' is not defined
I'm hoping for the function to pass as normal, since there are no errors like this when other functions in my program use the self parameter. Online tutorials I have checked don't seem to run into this problem either, they can pass functions to other modules just fine.
The function is not inside a class, I tried putting it into the class and calling said class into the main module that way, but I appear to get the exact same error when attempting this.
Have I run into a circular dependency? Any suggestions to fix this problem?
You do not include self. Self is defined by the namespace.
legalMovesis the namespace.This is assuming chess is the called class, and your method
legalMovesis inside that class. Otherwise you shouldn't be usingselfat all.If you are bringing legalMoves in from a chess.py, then you do not need self, and define your function without the variable
self