i have something that requires a matrix of values, similar to pokemon:
i have a class object for each of the types, is there a pattern or a good way to implement this, as a middle layer or in the classes?
i have something that requires a matrix of values, similar to pokemon:
i have a class object for each of the types, is there a pattern or a good way to implement this, as a middle layer or in the classes?
Yes, give a try to the Decorator design pattern.
hint: just create a Normal
class with all the stats you need. Then create a Decorator
class for each
row of the matrix: FireDecorator
, SteelDecorator
, that apply the multiplier for attack/defense.
bonus #1: you can build very easily a "Fire Steel Character", dynamically (the intent of the pattern)
bonus #2: when you add another character, say the "Giant", you just add one class, without touching anything else
You can use 2 maps (map in java, in other languages it can have another name): 1 for
Attacking-->Defending
and one for Defending-->Attacking
.
Let's consider Attacking-->Defending example. Map will contain Attacking types as keys and arrays of Defending types as values. For example:
Fire-->[Fire, Water, Grass, Ice, Bug, Rock, Dragon, Steel]
If you have a separate class for each "thing" that these types qualify (your pokemon or whatever) the classes could hold a static hash / map / dictionary structure that gives what multipliers there are for attacking the others. Such a hash would represent one row of the table. If you really need the reverse lookup, just make one more that stores the column of information.
A dictionary uses the names of the attacker (Fire, Ice etc) as key that contains dictionaries which use the names of the defender as keys and the multiplers as values.
It's a basic multiple-dispatch problem. Unfortunately, most languages do not support multiple dispatch.
So I would probably use a map of maps. The outer map maps attacks to maps of defenses, which in turn map defenses to scores/effects/whatever.
You could use the Visitor pattern, but that gets cumbersome fast.
In Python, assuming that you aren't using much subclassing (e.g. no subclasses of Ice), you could use a dictionary mapping (attack,defense)
tuples to scores. That would be a rather clean solution and would be supported by a variety of languages (all you need is a Pair class and an ability to represent attack types as objects, either via a class object or something like an enum).
Why make it so complicated - For the sake of maintenance make it like it looks. A two dimensional array will do fine and since it is static will give you best lookup performance - You then just need a way to go from Name/Type to array index.