2

I thought I might be able to calculate the rounds won value by subtracting deaths from number of rounds, but my counters are not being incremented:

public void onRoundEnded(RoundEndedEvent event) 
{
    roundCount++;
}

public void onDeath(DeathEvent event)
{
    deathCount++;
}

Not getting any compile errors or any other errors in the log. When I output the variables to the log in the onBattleEnded event, the output (after 100 rounds) is:

roundCount=1
deathCount=0

Full code below:

public class AB extends AdvancedRobot
{
    private int deathCount;
    private int roundCount;

    public void run() 
    {
        while(true) 
        {
            ahead(100);
            turnGunRight(360);
            back(100);
            turnGunRight(360);
        }
    }

    public void onScannedRobot(ScannedRobotEvent e) 
    {
        fire(1);
    }

    public void onHitByBullet(HitByBulletEvent e) 
    {
        back(10);
    }

    public void onHitWall(HitWallEvent e) 
    {
        back(20);
    }

    public void onRoundEnded(RoundEndedEvent event) 
    {
        roundCount++;
    }

    public void onDeath(DeathEvent event)
    {
        deathCount++;
    }

    public void onBattleEnded(BattleEndedEvent event) 
    {   
        System.out.println("roundCount=" + roundCount);
        System.out.println("deathCount=" + deathCount);
    }
}

Robocode version used is 1.9.2.6

lepton
  • 715
  • 1
  • 6
  • 22
  • 1
    And what do you expect it to do? Can you post a [Minimal, Complete, and Verifiable example?](https://stackoverflow.com/help/mcve) – Koekje Apr 11 '17 at 22:07
  • I expect the roundCount to be incremented after each round has ended, and the deathCount to be incremented each time the robot is killed. When I run a battle with 100 rounds, roundCount=1 and deathCount=0. – lepton Apr 11 '17 at 22:12
  • There is a possibility that each method is not being called, which would mean the problem is elsewhere in your code. Could you please do some quick debugging and verify that they are being called? Just put System.out.println("round ended"); and System.out.println("died"); at the top of each method. – Nicholas Greene Apr 11 '17 at 22:14
  • 1
    Or perhaps a new instance is created each time? Or the fields reset? A full example would be nice... – Koekje Apr 11 '17 at 22:15
  • Example added to my first post. – lepton Apr 11 '17 at 22:26
  • @Nicholas Greene - I added the log messages and the events are being triggered, but the counters are not being incremented. – lepton Apr 11 '17 at 22:27
  • 2
    Does making the fields static work? – Koekje Apr 11 '17 at 22:43
  • @Koekje - thanks, that's fixed it. – lepton Apr 11 '17 at 22:51
  • Your welcome, added an answer for this :) – Koekje Apr 11 '17 at 22:55

1 Answers1

2

So a new instance is created for each round. Making the fields static makes it a class variable, which is shared by each instance as well. You can find more information here.

Koekje
  • 677
  • 1
  • 6
  • 17