Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: detecting object name?

Tags:

java

class

I am working on a little tiny game, where there is a Attacker and a Defender.

Player Attacker = new Player();
Player Defender = 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 have commented inside the code above, where i wish to have a if statement to determine how many dices it should have.

If this is not possible to do, another way of doing this maybe?

I also tried to

Attacker.tarningar = 3;
Defender.tarningar = 2;

right under where the object gets defined in main, but it doesn't work, because it has already ran Player() inside class.

(I'm still new to java) Thanks

like image 689
Karem Avatar asked Jul 16 '26 06:07

Karem


2 Answers

Maybe 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 tell the player if it is attacking or defending when it is constructed.

Player p = new Player(true); // creates an attacker
like image 160
jjnguy Avatar answered Jul 18 '26 20:07

jjnguy


You should add a variable determining whether this is an attacker or a defender. Or even better, if they do different things, create subclasses for attacker and defender.

like image 23
MByD Avatar answered Jul 18 '26 21:07

MByD