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

查看:35
本文介绍了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 点生命值!

Hero loses 1 health!

非常感谢任何帮助,提前致谢.

Any help is much appreciated, thanks in advance.

推荐答案

while 循环只会在两个操作之后进行评估.你需要一种在英雄击中怪物后打破循环的方法.我会亲自更改 checkAlive 方法以返回一个布尔值,并将命中方法放在 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天全站免登陆