字符串中的所有元素都较低

时间:2015-05-20 00:33:57

标签: c++ string

晚上好!   为了完成我的BattleShip游戏,我需要一个gameOver函数来查明字符串的一半字符是否较低。我的意思是,每个字符串都命名一艘船: - 例如,我有一艘由char P size 4代表的船,他的字符串状态为:PPPP。

每当我攻击船位时,我击中的角落就会降低。当一半的火星被摧毁时,船只会下沉。

bool Ship::isDestroyed() const{

    int tam;
    tam = status.length();

    cout << tam;

    int i = 0;
    int lowercase;
    lowercase = 0;

    lowercase = 0;
    for (int i = 0; i < tam; i++){
        if (islower(status[i])){
            lowercase++;
            cout << "lowercase" << lowercase << endl;
        }
    }
    cout << "lowercase" << lowercase << endl;

    if (lowercase == tam / 2){
        cout << (int)tam / 2 << endl;
        cout << "lowercase fail" << lowercase << endl;
        return true;
    }
    else
        return false;
}

bool Board::gameOver() {
    for (int i = 0; i < ships.size() - 1; i++){
        if ((ships[i].isDestroyed())){
            return false;
            continue;
        }

    }
    cout << "GameOver" << endl;
    return true;
}

ships.size() - 将Ship对象放在其中。

我猜问题是gameOver,但我真的可以解决它。

1 个答案:

答案 0 :(得分:2)

您的功能gameOver不会检查所有船只,因为返回声明:

if((ships[i].isDestroyed())){
        return false; // LOOK HERE!!! :(
        continue;
    }

你必须检查所有船只是否已被销毁。

解决方案:

我为此更改了您的代码:

#include <algorithm>  //for count_if()

bool islower(char a){
    if( tolower(a) == a ) return true;
    else return false;
}

bool Ship::isDestroyed() const{ 
    // This is not necessary(You can let your isDestroyed function without any changes)

    //This counts those chars that satisfy islower:
    int lowercase = count_if (status.begin(), status.end(), islower); 
    return ( lowercase <= (status.length/2) ) ? true : false;
}

bool Board::gameOver() {
    bool is_the_game_over = true;
    for(int i = 0 ; i < ships.size() ; i++){
        if( ships[i].isDestroyed() == false ) { 
            //There is at least one ship that is not destroyed.
            is_the_game_over = false ;
            break;
        }
    }       
    return is_the_game_over;
}