For example, I have a game with some characters have 5 elements:fire,water,wood,light,dark.
the element has weakness which attack power will increase for some elements:
fire>wood
water>fire
wood>water
light>dark
dark>light
eg:
fire hit wood,the power is *2
fire hit water,the power is *0.5
I have a function to get the relation between element and factor:
float getFactor(string me,string enemy){
if(me=="fire"){
if(enemy=="fire"){
return 1;
}else if(enemy=="water"){
return 0.5;
}else if(enemy=="wood"){
return 2;
}else if(enemy=="light"){
return 1;
}else{
return 1;
}
}else if(me=="water"){
if(enemy=="fire"){
return 2;
}else if(enemy=="water"){
return 1;
}else if(enemy=="wood"){
return 0.5;
}else if(enemy=="light"){
return 1;
}else{
return 1;
}
}else if(me=="wood"){
if(enemy=="fire"){
return 0.5;
}else if(enemy=="water"){
return 2;
}else if(enemy=="wood"){
return 1;
}else if(enemy=="light"){
return 1;
}else{
return 1;
}
}else if(me=="light"){
if(enemy=="fire"){
return 1;
}else if(enemy=="water"){
return 1;
}else if(enemy=="wood"){
return 1;
}else if(enemy=="light"){
return 1;
}else{
return 2;
}
}else{
if(enemy=="fire"){
return 1;
}else if(enemy=="water"){
return 1;
}else if(enemy=="wood"){
return 1;
}else if(enemy=="light"){
return 2;
}else{
return 1;
}
}
}
which getFactor("fire","water") will return 0.5;
this function works, but it has too much lines and too much if else statement,also it seems very hard to maintain if I add a new element to it.
is there any method to implement the table but in more maintainable code style and less line of codes?
If you want a table, use a table:
Now you just do
to get the attack power. This approach requires that you store the element type as an enum value instead of as a string, but that's better coding style anyway for C++ since it limits the space of possible elements to the ones that are actually defined, and makes lots of functions really easy.
Another example of tables being useful: