0

I am writing a chess game and I need to set the property self.selected of every instance of a chess piece (except the instance of the chess piece I have just clicked) equal to False when a chess piece is clicked and thus self.selected is set to True.

I think the problem is that I am binding left mouse click to the object after it is drawn in the super class and so I can't return to a global function which can manage the different instances externally.

Basically (in case i am going about this all wrong), I have my chess pieces, and when I click one it's property self.selected becomes True. I need to set that property to False again if a different chess piece is selected or if that same chess piece is clicked again.

OliverGriffin
  • 370
  • 3
  • 17

1 Answers1

0

This is easy to do with a class variable and a property:

class ChessPiece(object):
    selected_piece = None  # class variable

    def select(self):      # call this on the piece that's been clicked upon
        ChessPiece.selected_piece = self

    @property
    def selected(self):    # test this attribute to see if a piece is curently selected
        return ChessPiece.selected_piece is self

You could use a global variable instead of a class variable if you want, you'd just need a global statement in the select method if you do, so that it can modify the global variable rather than a local one.

You could also use a setter of the property rather than a separate select method, but that would require (slightly) more complicated code to handle things like setting selected to False when it was already False.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • Sorry, I'm new to oop, do you have any tutorials you could recommend for properties as I've never seen them before. Also, why did you pass in object? – OliverGriffin Aug 16 '15 at 08:45
  • Start with the [official docs](https://docs.python.org/3/library/functions.html#property), perhaps, then look for [other answers](http://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work)? – Blckknght Aug 16 '15 at 22:43