Reputation: 3
I am attempting to create a Pawn class for a chess game, but I get the error "NameError: name 'self' is not defined" in the "can_move" function's first if statement, even though I define the colour as the input in the initialise function? Any ideas?
class Pawn(object):
def __init__(self, x, y, colour):
#store the pawns coords
self.x = x
self.y = y
#store the colour of the piece
self.colour = colour
#store if it moved yet or not
self.moved = False
self.print_value = self.colour+"P"
def can_move(newx, newy):
#func to check if piece can move along those coords
if self.colour == "W":
pieces = game_tracker.live_white
elif self.colour == "B":
pieces = game_tracker.live_black
Upvotes: 0
Views: 929
Reputation: 16711
You need to add self as an argument, representing the current instance of the class. Also indent.
class Pawn(object):
def __init__(self, x, y, colour):
#store the pawns coords
self.x = x
self.y = y
#store the colour of the piece
self.colour = colour
#store if it moved yet or not
self.moved = False
self.print_value = self.colour+"P"
def can_move(self, newx, newy):
#func to check if piece can move along those coords
if self.colour == "W":
pieces = game_tracker.live_white
elif self.colour == "B":
pieces = game_tracker.live_black
Upvotes: 1
Reputation: 43314
Instance methods need self
as first argument
def can_move(self, newx, newy):
Otherwise the method does not know which instance it is operating on
Upvotes: 2