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
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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.