该游戏将一系列的单词存储在一个string对象数组中,然后随机选择一个单词,让人猜测单词的字母。如果猜错6次,玩家就书了。该程序使用find()函数来检查玩家的猜测,使用+=操作符创建一个string对象来记录玩家的错误猜测。为记录玩家才对的情况,程序创建一个单词,其长度与被猜测的单词相同,但包含的是连字符,玩家才对字符时,将用该字符替换相应的字符。
下面是源码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
using std::string;
const int NUM = 26;
const string wordlist[NUM]={
"apiary","beetle","cereal","danger",
"ensign","florid","garage","healtn",
"insult","jackal","keeper","loaner",
"manage","nonce","onset","plaid",
"quilt","remote","stolid","train",
"useful","valid","whence","xenon",
"yearn","zippy"
};
int _tmain(int argc, _TCHAR* argv[])
{
using std::cout;
using std::cin;
using std::tolower;
using std::endl;
std::srand(std::time(0));
char play;
cout << "Will you play a word game? <y/n>";
cin >> play;
//字符转小写
play = tolower(play);
while(play == 'y')
{
//随机产生一个字符串
string target = wordlist[std::rand() % NUM];
int length = target.length();
//构造长度length的-
string attempt(length,'-');
//记录错误的字符串
string badchars;
int guesses = 6;
cout << "Guess my sercet word,It has"<<length
<< " letters, and you guess\n"
<< "one letter at a time.You get"<<guesses
<< "wrong guesses.\n";
cout << "Your word: "<< attempt << endl;
while(guesses > 0 && attempt != target)
{
char letter;
cout << "Guess a letter: ";
cin >> letter;
//string::npos是sting类的静态成员,它的值是string对象能存储的最大字符数
//badchars或attempt中已有letters
if(badchars.find(letter) != string::npos || attempt.find
(letter) != string::npos)
{
cout << "You already guessed that.Try again.\n";
continue;
}
int loc = target.find(letter);
if(loc == string::npos)
{
cout << "Oh,bad guess!\n";
--guesses;
badchars += letter;
}
else
{
cout << "Good guess!\n";
attempt[loc] = letter;
//如果找到了,则下一次搜索位置从loc+1开始
loc = target.find(letter,loc+1);
while(loc != string::npos)
{
attempt[loc] = letter;
loc = target.find(letter,loc+1);
}
}
cout << "Your word:"<<attempt<<endl;
if(attempt != target)
{
if(badchars.length()>0)
{
cout << "Bad choices: "<< badchars<<endl;
}
cout << guesses << "bad guesses left\n";
}
}
if(guesses > 0)
cout << " That's right\n";
else
cout << "Sorry,the word is"<< target << ".\n";
cout << "Will you play another? <y/n>";
cin >> play;
play = tolower(play);
}
cout << "Bye.\n";
return 0;
}
下面是效果图:
本程序源码来自c++ primer plur 第五版 中文版