Reputation: 575
Just to play around a little, I'm trying to make a turn-based battle game with two players through command line. Each player controls a monster with up to 4 different moves. I have defined Monster and Move classes to define the different monsters and moves. When a player uses a move, I'm thinking I want to call something like a performOn(Monster mon) method in the move to use. In that method I want to define the implementation for what the move does, since not every move will do the same thing. I'm pretty sure Java can do this but I'm not entirely sure how it's done. For both the Monster and Move classes, I have an inner Builder class to avoid big constructor methods. And if anyone has a better idea of how to perform a move, please feel free to share. :)
Thanks!
Example:
// moves is a HashMap<String, Move>
monster1.moves.get("Firebreath").performOn(monster2); // damages monster2
monster2.moves.get("Heal").performOn(monster2); // heals monster2
Upvotes: 1
Views: 595
Reputation: 143856
You can either make a super class for Move
and all the special moves can extend it:
public abstract class Move
{
public abstract void performOn(Monster m);
}
And then extend:
public class FirebreathMove extends Move
{
public void performOn(Monster m)
{
// do something to Monster
}
}
Or you can create an interface:
public interface Move
{
public void performOn(Monster m);
}
And your moves can implement it:
public class FirebreathMove implements Move
{
public void performOn(Monster m)
{
// do something to Monster
}
}
In either case you'd have a reference to a Move
that you can call performOn(Monster)
, but it depends on whether all moves share some kind of common functionality that you want to subclass (first method, with superclass) or if Moves can also be other things and you just need the performOn(Monster)
method signature. For example, if you had something like a Weapon, that has a Move:
public class FancyWeapon extends Weapon implements Move
{
}
Upvotes: 2
Reputation: 5094
You could have a Move parent class(or interface) so it works out similar to this.
public interface Move{
public void performOn(Monster m);
}
public Firebreath implements Move{
public void performOn(Monster m)
{
m.takeFireDamage(5);
}
}
public Heal implements Move{
public void performOn(Monster m)
{
m.healDamage(5);
}
}
Upvotes: 1
Reputation: 1012
I'm not sure if this is what you mean, but an interface
could be what you're after?
An interface would look like this:
public interface Move() {
void performOn(Object o);
String getMoveName();
}
That example, you'd then make a series of classes:
public class BreatheFire implements Move {
@Overrides
public void performOn(Object o) {
....
}
}
.
Hope that helps!
Upvotes: 1