programing

최대 값을 초과하지 않고 어떻게 변수를 증가시킬 수 있습니까?

nasanasas 2020. 9. 6. 10:07
반응형

최대 값을 초과하지 않고 어떻게 변수를 증가시킬 수 있습니까?


저는 학교를위한 간단한 비디오 게임 프로그램을 작업 중이며 해당 메서드를 호출하면 플레이어가 15 체력 포인트를 얻는 메서드를 만들었습니다. 나는 건강을 최대 100으로 유지해야하고이 시점에서 제한된 프로그래밍 능력으로 나는 이런 일을하고있다.

public void getHealed(){
    if(health <= 85)
        health += 15;
    else if(health == 86)
        health += 14;
    else if(health == 87)
    health += 13; 
}// this would continue so that I would never go over 100

나는 내 구문이 완벽하지 않다는 것을 이해하지만 내 질문은 더 나은 방법이 될 수 있다는 것입니다.

이를 포화 산술 이라고 합니다.


그냥 할 것입니다. 기본적으로 최소 100 (최대 체력)과 추가 점수 15 점 사이의 체력이 필요합니다. 사용자의 건강이 100을 초과하지 않도록합니다.

public void getHealed() {
    health = Math.min(health + 15, 100);
}

히트 포인트가 0 아래로 떨어지지 않도록 유사한 함수를 사용할 수 있습니다 Math.max..

public void takeDamage(int damage) {
    if(damage > 0) {
        health = Math.max(health - damage, 0);
    }
}

체력에 15 만 더하면됩니다.

health += 15;
if(health > 100){
    health = 100;
}

그러나 Bland가 언급했듯이 때때로 멀티 스레딩 (한 번에 여러 코드 블록 실행)을 사용하면 어떤 시점 에서든 상태가 100을 넘으면 문제가 발생할 수 있으며 상태 속성을 여러 번 변경하는 것도 좋지 않을 수 있습니다. 이 경우 다른 답변에서 언급했듯이 이렇게 할 수 있습니다.

if(health + 15 > 100) {
    health = 100;
} else {
    health += 15;
}

int위의 각각에 대해 별도의 케이스가 필요하지 않습니다 85. 하나만 가지고 else건강이 이미 86이상이면으로 직접 설정하십시오 100.

if(health <= 85)
    health += 15;
else
    health = 100;

나는이 일을 관용적, 객체 지향 방법은을 가지고 생각 setHealthCharacter클래스입니다. 해당 메서드의 구현은 다음과 같습니다.

public void setHealth(int newValue) {
    health = Math.max(0, Math.min(100, newValue))
}

This prevents the health from going below 0 or higher than 100, regardless of what you set it to.


Your getHealed() implementation can just be this:

public void getHealed() {
    setHealth(getHealth() + 15);
}

Whether it makes sense for the Character to have-a getHealed() method is an exercise left up to the reader :)


I am just going to offer a more reusable slice of code, its not the smallest but you can use it with any amount so its still worthy to be said

health += amountToHeal;
if (health >= 100) 
{ 
    health = 100;
}

You could also change the 100 to a maxHealth variable if you want to add stats to the game your making, so the whole method could be something like this

private int maxHealth = 100;
public void heal(int amountToHeal)
{
    health += amountToHeal;
    if (health >= maxHealth) 
    { 
        health = maxHealth;
    }
}

EDIT

For extra information

You could do the same for when the player gets damaged, but you wouldn't need a minHealth because that would be 0 anyways. Doing it this way you would be able to damage and heal any amounts with the same code.


health = health < 85 ? health + 15 : 100;

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 );

I know this is a school project, but if you wanted to expand your game later on and be able to upgrade your healing power, write the function like so:

public void getHealed(healthPWR) {
    health = Math.min(health + healthPWR, 100);
}

and call out the function:

getHealed(15);
getHealed(25);

...etc...

Furthermore you can create your max HP by creating a variable that is not local to the function. Since I don't know what language you're using, I will not show an example because it might have the wrong syntax.


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 believe this will do

if (health >= 85) health = 100;
else health += 15;

Explanation:

  • If the gap for healing is 15 or less, health will become 100.

  • Otherwise if the gap is bigger than 15, it will add 15 to the health.

So for example: if the health is 83, it will become 98 but not 100.


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));
}

Most simple way using the modulus operator.

health = (health + 50) % 100;

health will never equal or exceed 100.


   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;
    }

참고URL : https://stackoverflow.com/questions/18647214/how-can-i-increment-a-variable-without-exceeding-a-maximum-value

반응형