Reputation: 1122
I know this question is kind of simple and silly but I got stymied of searching the internet. Consider we have a 2-dimensional list in Python which represents a game board of hex and its elements would be changed by some function (like playing stone at some cell in the game board).
What I am looking for is a tool in Python that could define a function to be called whenever the value of any element in the array gets changed.
I already found the function trace
in tkinter which calls a function when StringVar
,DoubleVar
and so on get changed.
I was wondering if a similar one could be found for simple lists or even numpy lists.
Upvotes: 1
Views: 104
Reputation: 231395
Your requirements:
2-dimensinal list in python which represents a game board of hex
and its elements would be changed by some function (like playing stone at some cell in the game board).
a function to be called whenever the value of any element in the array gets changed.
The straight forward way to implement this is to define a class representing the board
and actions. It will contain the 2d list (could be numpy
array, but that may not be necessary).
It would also define methods that change the list, and perform the recording/callback.
class Board():
def __init__(...)
self.list2d=[] # 2d nested list
def record_play(...):
<action when a cell is changed>
def play(...):
<change self.list2d>
self.record_play(...)
As long a the Board
object controls all the changes, you don't need a more generic tracking tool, or even a subclass of list or array (though those are possible). Just make sure you call the tracking function each time you call the change function.
If you were doing this across different classes and kinds of objects it could be worth while constructing something more abstract. But for a one-off case, just do the obvious.
Upvotes: 1