I have an abstract sprite class (used to be called "Entity" but I changed it to sprite for some reason) and I wasn't sure how each type of sprite would draw itself, so I made a DrawStrategy interface and each Sprite holds one of these. So for instance, some sprites have 8 different images depending on what direction they are heading, some always use the same. Some have an animation cycle, some do not. I created different DrawStrategy classes for each type of drawing needed, and just add this to the Sprite when I create it.

The thing is, some strategies need more info than others. So I add methods like setDirection(Direction d) to a DirectionAnimationStrategy class (Direction is an Enum, BTW). But if a certain sprite child class (like Enemy) needs to call this, then I am forced to cast the DrawStrategy to DirectionAnimationStrategy. Here is what I am talking about:

By the way, Path is a class which tells the Enemy how it is to walk around the game world. I am making a tower defense game, just in case you missed my earlier thread, so enemies just walk along a predetermined path. I figured the best way to do this is to store the path as a spline.

There is no way that the code in enemy.updateMe can work unless the DrawStrategy it is given in the constructor is a DirectionAnimationStrategy. So the constructor should take a DirectionAnimationStrategy, and not a plain DrawStrategy. You can still treat it as a DrawStrategy (without any casting) for other methods that only need a DrawStrategy and don't otherwise need to be aware of the direction.

I tend to think of a Sprite as the mechanism for drawing in the first place, so a drawing strategy like how to animate is simply a property of the sprite. If I had a class that selected a different sprite based on its facing or position or whatever state, I might call it a Model, similar to a 3D model with rigging that can put into different poses. This is just my particular design taste, and I don't write action games (my experience is with MUDs) so take my design notes with a grain of salt...

This is the animation class that I use, I tried to cut out some extra stuff I had in that wasn't exactly relevant to animation. feel free to use any or all of it, it was designed to be stand-alone from my programs.

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org