string中的所有元素都是低的

All elements in string are lower

本文关键字:元素 string      更新时间:2023-10-16

大家晚上好!为了完成我的《战舰》游戏,我需要一个gameOver函数来发现字符串的一半字符是否较低。我的意思是,每个字符串代表一艘船:-例如,我有一艘船,用字符P表示,大小为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() - ships向量,里面有Ship对象。

我猜问题出在gameOver上,但我真的可以解决。

你的函数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;
}