while循环在需要时没有结束 [英] while loop not ending when required

查看:129
本文介绍了while循环在需要时没有结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,一些背景信息对我来说是编程的新手,并且仍在学习中,因此对我犯下的小错误深表歉意.我正在制作自己的基于文本的游戏,只是为了进一步练习等.

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.

以下是指向Dropbox上所有内容的链接,以获取更多上下文: https://www.dropbox.com/sh/uxy7vafzt3fwikf/B-FQ3VXfsR

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

我目前正在尝试为我的游戏实现战斗系统,并且遇到了战斗序列在需要时没有结束的问题. 战斗序列"是一个while循环,如下所示:

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

其中checkAlive()方法如下:

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
    {
        //
    }
}   

当英雄"或怪物"的生命值变为< = 0时,我试图让它结束战斗序列, 但是,当前正在完成while循环,因此即使英雄在第一击中杀死了怪物,也会产生被击中的结果.

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'

老鼠失去5点生命! 你杀了老鼠!

rat loses 5 health! You have killed the rat!

英雄失去1点生命!

非常感谢您提供任何帮助.

Any help is much appreciated, thanks in advance.

推荐答案

while循环仅在两个操作之后才求值.您需要一种在英雄击中怪物后打破循环的方法.我将亲自更改checkAlive方法以返回一个布尔值,并将hit方法放入while循环的if语句中:

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

这篇关于while循环在需要时没有结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆