hangman游戏

来源:互联网 发布:随身带着淘宝去异界txt 编辑:程序博客网 时间:2024/09/21 08:57

这次帮一个在加拿大读研的兄弟写了一个hangman猜单词的游戏,顺便记录一下:
hangman是一个猜单词的游戏,闯关者每次猜一个英文字母,猜错了就离小人死亡更进一步,当小人死亡游戏失败;在离小人还没被上吊前猜对英文单词,小人获救,游戏胜利。

#include <iostream>#include <string>using namespace std;//Word存放要猜的单词//WordLen是要猜的单词的长度//guest是猜的字母//life是生命值string Word;int WordLen;char guest;int life = 10;//初始化函数void init(){    cout<<"input a word to guest"<<endl;    cin>>Word;    WordLen = Word.length();    cout<<"the number of word is"<<WordLen<<endl;}//判断函数int judge(int &left, char x){    //ok用于命中计数    //status看返回的状态,0是正常返回,1是死亡,2是胜利    int ok = 0;    int status =0;    //用STL的迭代器遍历单词,得到命中个数ok    string::iterator it;    for(it = Word.begin();it != Word.end();++it){        if (x == *it){            ok++;        }    }    //用STL的erase和remove配合删除单词中已经命中的字母    //remove返回假删除数组后的新结尾    //erase真正删除    Word.erase(remove(Word.begin(),Word.end(),x), Word.end());    if(ok){        cout<<guest<<"  hit the target!"<<endl;    }else{        cout<<"miss it!"<<endl;        life--;    }    left = left - ok;    if(left <= 0 && life <=0){        status = 1;    }else if(left <=0 && life >0){        status = 2;    }    return status;}int main(){    init();    //剩余需要猜的字母数    int left = WordLen;    //循环的最大次数=生命值+要猜的字母数    int LoopMax = life + WordLen;    for(int count=0;count<LoopMax;++count){        cout<<"now you guest:"<<endl;        cin>>guest;        int result;        result = judge(left, guest);        if(result == 1 || life <= 0){            cout<<"the man die!"<<endl;            cout<<"game over !"<<endl;            return 0;        }else if(result == 2){            cout<<"you win!"<<endl;            return 0;        }        cout<<"you have left "<<left<<" letter to guest"<<endl;        cout<<"your life is "<<life<<endl;    }    return 0;}
0 0
原创粉丝点击