I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at
If I wanted to be thread safe I'd do it this way rather than using a synchronized block.
The atomic compareAndSet achieves the same outcome as synchronized without the overhead.
AtomicInteger health = new AtomicInteger();
public void addHealth(int value)
{
int original = 0;
int newValue = 0;
do
{
original = health.get();
newValue = Math.min(100, original + value);
}
while (!health.compareAndSet(original, newValue));
}
just add 15 to the health, so:
health += 15;
if(health > 100){
health = 100;
}
However, as bland has noted, sometimes with multi-threading (multiple blocks of code executing at once) having the health go over 100 at any point can cause problems, and changing the health property multiple times can also be bad. In that case, you could do this, as mentioned in other answers.
if(health + 15 > 100) {
health = 100;
} else {
health += 15;
}
Maybe this?
public void getHealed()
{
if (health <= 85)
{
health += 15;
} else
{
health = 100;
}
}
If you want to be cheeky and fit your code on one line, you could use a ternary operator:
health += (health <= 85) ? 15 : (100 - health);
Note that some people will frown upon this syntax due to (arguably) bad readability!
I would make a static method in a helper class. This way, rather than repeating code for every value which need to fit within some boundaries, you can have one all purpose method. It would accept two values defining the min and max, and a third value to be clamped within that range.
class HelperClass
{
// Some other methods
public static int clamp( int min, int max, int value )
{
if( value > max )
return max;
else if( value < min )
return min;
else
return value;
}
}
For your case, you would declare your minimum and maximum health somewhere.
final int HealthMin = 0;
final int HealthMax = 100;
Then call the function passing in your min, max, and adjusted health.
health = HelperClass.clamp( HealthMin, HealthMax, health + 15 );
private int health;
public void Heal()
{
if (health > 85)
health = 100;
else
health += 15;
}
public void Damage()
{
if (health < 15)
health = 0;
else
health -= 15;
}