I've been working on a python module that implements a base-class for a text-based board game. The class is meant to be used as a "game engine", to be imported by other python programs that define custom user-interfaces to the game.
Each instance of the class represents a game match, with which one can communicate by calling the appropriate methods, to register players, enter user actions, change game settings, check the state of the game, etc.
The game logic isn't itself troublesome, but in my efforts to make the class robust I find my code is getting extremely cluttered. The problem is making sure that every interaction with the game is valid, both "structurally":
- that no player is added to the game twice
- that only commands by users that have joined the game are executed.
- that only command issued in the appropriate game stage are executed, etc.
and within the context of the game:
- that the user is referencing valid game-objects
- that the user had the resources available for such a command, etc.
That is, I need to make sure that both the actions of the interface-program and those of the users are valid. Naively making these consistency checks within my class, however, is hiding the the game-logic, and making developing and parsing the code much more burdensome than it should.
I've thought of wrapping the game-class in a validator class that would make the appropriate checks before running each game-class method, thus decoupling the validating part, but was afraid the separation might not be so clean-cut and the code might get too fragmented.
When dealing with attributes, python has great concepts, such as descriptors and the @property
decorators. Is there something analogous for methods?
I'm sure that's a fairly standard problem, what is the design pattern to help alleviate it?
Aucun commentaire:
Enregistrer un commentaire