0
\$\begingroup\$

I am making a android game, and it is supposed to have attacks.(Note, this game is 2D). I have implemented things like movement to the base, but I am not too sure about the actual attack algorithm. There are supposed to be to bases, one attacker and one defender. I have tried multiple ways, but I cannot get it realistic enough. Here is what has to be a part of it:

    public void attackCalculations(){
        Random r = new Random();

        int[] aa = att.ARMIES;
        int[] ab = def.ARMIES;

    }

I thought about making random casualties based on who have more troops(attacker or defender), but it will not work(tested it, and the casualties were often 0, and it was a loss for the attacker...) There are ten troops(the ARMIES-variable is a array-int with a max of 10)

    int ARMIES = new int[10];

So, how can I calculate who wins based on all the troops(cannot make a single integer due to different troops)?

\$\endgroup\$
0
\$\begingroup\$

First of all, I would make your troops into just an integer: the number of units. If you don't want to do that, just use the array length as a gauge for their troop sizes.

Now the easiest way to do this would be to just take the amount of attacking troops away from the amount defending troops. If the result is negative, the attackers win.. yet if the result is positive, the defenders win and if it's 0 its a draw.

Then to add random casualties, you just add a randomly generated number from -1 to 1 and add it to the result.

Random random = new Random();   
int result = defender - attacker;

result += (random.nextInt(3) - 1);

System.out.println(result);
if(result < 0) {
    System.out.println("Attacker Wins");
} else if(result == 0) {
    System.out.print("Draw");
} else if(result > 0) {
    System.out.print("Defender Wins");
}

This is good because, if you ever have 10 Attackers battling 9 Defenders, you have a larger bias towards the attackers (because they have more troops) and yet it still gives the possibility for there to be a stalemate.

As you see these results below show how each of 10 battles turned out, with the attacker having 10 troops and the defender having 9:

enter image description here

As expected, the attacker has won most times because they have a greater amount of troops, and yet there is still a small chance for a draw to occur.

If your troops all have different stats, you can then just take and add them to the result variable as you please.

\$\endgroup\$
0
\$\begingroup\$

Try a risk like aproach. N dice launch from attackers sorted by result. M dice launch from defenders sorted by result. For each pair of results count att casualities and def casualities. In risk with the same result defender wins. You can set a max number of comparations per turn

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy