while loop not ending when required

房东的猫 提交于 2019-12-02 18:46:41

问题


So some background information, I'm new to programming and am still learning, so I apologize for my trivial error making. I am making my own text based game just to further practice etc.

Here is the link to everything on dropbox for more context: https://www.dropbox.com/sh/uxy7vafzt3fwikf/B-FQ3VXfsR

I am currently trying to implement the combat system for my game, and I am running into the issue of the combat sequence not ending when required. The 'combat sequence' is a while loop as follows:

public void startCombat()
{

    inCombat = true;

    while(inCombat != false)// && herohealth > 0 && monsterhealth > 0)
    {
        checkAlive();
        heroHitMonster();
        checkAlive();
        monsterHitHero();           
    }          

    attackinghero.setHeroHealth(herohealth);
    attackedmonster.setMonsterHealth(monsterhealth);
}

where the checkAlive() method is as follows:

public void checkAlive()
{    
    if(herohealth <= 0)
    {            
        System.out.println("You have died.");
        attackinghero.clearInventory();
        inCombat = false;

    }

    else if(monsterhealth <= 0)
    {         
        System.out.println("You have killed the "+attackedmonster.getmonsterName()+"!");
        inCombat = false;
        combatlocation.removeMonster(attackedmonster.getmonsterName());
    }    

    else
    {
        //
    }
}   

I am trying to get it to end the combat sequence when either the 'hero' or 'monster' health become <= 0, however it is currently finishing the while loop and therefore producing the result of the hero being hit even if he killed the monster in his first hit.

This is what is currently being 'printed to screen'

rat loses 5 health! You have killed the rat!

Hero loses 1 health!

Any help is much appreciated, thanks in advance.


回答1:


checkAlive shouldn't be void it should be Boolean and should return inCombat, and in your function startCombat you should do inCombat=checkAlive();




回答2:


The while loop will only evaluate after both actions. You need a way to break the loop after the hero hits the monster. I would personally change the checkAlive method to return a boolean, and put the hit methods in if statements in the while loop:

if(checkAlive())
{
    heroHitMonster();
}
if(checkAlive())
{
    monsterHitHero();
}



回答3:


You should end the loop at the end of the checkAlive instead of changing the boolean value. If you killed the monster at first hit, you still execute the monsterHitHero() even, if the monster is killed. The function to hit should be conditioned to the life of heroes/monster.



来源:https://stackoverflow.com/questions/21809453/while-loop-not-ending-when-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!