1

I am making a simple game. When I call the fight method the damage received by the character when it is hit is its own damage variable For example Knight- Health: 100 Damage: 20

Soldier- health: 100 Damage: 10

when I call my method an the knight attacks the soldier and the soldier attacks the knight their health is as follows

Knight-> 80 Health Soldier-> 90 Health

when it should be the other way round

example code

public abstract class BasicCharacter 
{
private double health;
private double damage;
private double attackProbability;
private String name;


public BasicCharacter(double hp,double attp,double d, String n)
{   
    health=hp;
    attackProbability=attp;
    damage=d;
    name=n; 


}


public void setHealth(double hp)
{  
    health=hp;
}

public double getHealth()
{
    return health;
}



public double getDamage()
{
    return damage;
}




public void fight()
{


    double prob=Math.random();

    if(prob<attackProbability)
    {
        JOptionPane.showMessageDialog(null, name+" attacked for " + damage+    "\n" + name + " health " + health +" left");
        health=health-damage;
    }
    else {

        JOptionPane.showMessageDialog(null, name + " missed");
    }


}
}

both the soldiers and the knight are subclasses of BasicCharacter

  public class soldier extends BasicCharacter{} 

thanks

0

2 Answers 2

3

It is because in your fight() method, you are deducting the health from the object's own damage:

health=health-damage;

What you actually wants is probably:

fight(BasicCharacter target){
    target.setHealth(target.getHealth() - this.damage);
}

You can add an argument to your fight method which indicates the fighting target.

Sign up to request clarification or add additional context in comments.

2 Comments

would this be in the same method or a separate method as all characters are part of this class
@thebigone You can implement this in the abstract class for BasicCharacter. So whoever extends BasicCharacter will have this defaut implementation. You may still choose to override this method in the subclass.
0

Example: Knight attacking Soldier

A simple method that will handle the damaging, send in object you want to damage and the amount of damage.

public void damaging(Object object, Double damage){
 if(object instanceof Soldier){
 ((Soldier)object).setHealth(((Soldier)object).getHealth()-damage);
 }
}

1 Comment

Why should someone use Object? You don't even want an Object here, since this method can only work with Soldier. So how about using either Soldier or better BasicCharacter instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.