I've got a Python project wherein a basic object is created and various different attributes are modified/given to it via what I thought was a good example of a strategy pattern.
In this silly game there are enemies with multiple different potential patterns of movement. The Enemy class has a basic pattern of movement it defaults to; otherwise, a strategy pattern is implemented to randomly choose different ones as the game progresses.
The Enemy's obj.update()
is something like this:
def update(self):
self.unique_action()
self.check_if_shooting()
self.find_new_rect()
So I'd been replacing self.unique_action
on the fly with a strategy pattern using what I think are called 'higher-order functions'.
def new_pattern_of_movement(obj, func):
def inner(*args, **kwargs):
##code for doing different stuff
##intentionally NOT returning the function -
##the idea is to replace the default unique_action
return inner
…
##eventually when generating bad guys for the level…
newEnemy = Enemy()
new_AI = random.choice([new_pattern_of_movement, other_pattern, some_other_pattern]) #etc etc
newEnemy.unique_action = new_AI(newEnemy, newEnemy.unique_action)
After a while, I thought, "self, why not change their attributes as part of the wrapper as well? you change their methods, just set their point_value and graphics and all that dumb stuff too" and I was like "welp I can do that"
def alt_action(obj):
def inner(*args, **kwargs):
##code for their unique_action
##again, not returning obj.unique_action
obj.point_value += 100
obj.color = colors.YELLOW
obj.speed -= 1
return inner
Evidently, this is regarded as "very JavaScript-y". I find it terribly simple though, and preferable to stringing along a bunch of objects that inherit from a long chain of ancestors.
My job isn't on the line or anything here, but in such a situation is it really that critical to split these up into separate classes? The first example, at the least, seems fine because it really is just replacing one method with another, but in the second example, I'm definitely redefining object attributes, and I go a bit further than depicted here (replacing the object's self.draw()
methods and that if it's necessary).
It might be bad, but it's so stupidly easy.
Is this a good example of how not to implement a strategy pattern?