Java: determining the name of an object?

I am working on a small tiny game where there is an attacker and defender.

        Player Attacker = new Player();
        Player Deffender = new Player();

    }
}
class Player{
    int armees = 0;
    int tarningar = 0;
    Dice Dices[];
    Player(){
        armees = 10;
        // if object name is Attacker, tarninger = 3, if defender = 2
        Dices= new Dice[tarningar];
        for(int i=0;i<Dices.length;i++){
            Dices[i]=new Dice();
        }
    }
}

I commented inside the above code where I want to have an if statement to determine how many cubes it should have.

If this is impossible to do, maybe another way to do it?

I also tried

Attacker.tarningar = 3;
Deffender.tarningar = 2;

right in the place where the object is mainly defined, but it does not work, because it already executed Player () inside the class.

(im still new for java) thanks

+3
source share
4 answers

Perhaps you could do:

Player(boolean isAttacker){
    armees = 10;
    // if object name is Attacker, tarninger = 3, if defender = 2
    int diceNum;
    if (isAttacker) diceNum = 2;
    else diceNum = 3;
    Dices= new Dice[diceNum];
    for(int i=0;i<Dices.length;i++){
        Dices[i]=new Dice();
    }
}

Then you will need to inform the player that he is attacking or defending when he is created.

Player p = new Player(true); // creates an attacker
+2
source

change your code to this:

  Player Attacker = new Player(true);
        Player Deffender = new Player(false);

    }
}
class Player{
    boolean attacker;
    int armees = 0;
    int tarningar = 0;
    Dice Dices[];
    Player(boolean attacker){
        this.attacker = attacker;
        armees = 10;
        tarninger = attacker ? 3 : 2;
        Dices= new Dice[tarningar];
        for(int i=0;i<Dices.length;i++){
            Dices[i]=new Dice();
        }
    }
}
+2
source

, , . , , .

+2

If you are trying to differentiate based on variable names, this is not possible because this information is deleted during compiler optimization. If instances are available, you can do

if (this == attacker)
{
    ...
}

or you can enter a new field to store the name

Player attacker = new Player("Attacker");

or perhaps an enumeration.

Player attacker = new Player(PlayerType.Attacker);
+1
source

All Articles