/******************************************************************** * Runs the naming game for a maximum of <rounds> rounds ********************************************************************/ void NamingGame::run(uint rounds) { uint sender, receiver; srand(time(NULL)); std::string word; // For am maximum of <rounds> rounds for (int i = 0; i < rounds; ++i) { // Choose one random node (sender) sender = chooseNode(); // Choose one random neighbor (receiver) receiver = chooseNeighbor(sender); if (receiver == -1) { --i; continue; } // Choose one random word from the sender; word = chooseWord(sender); // Send him a random word. Hijinks ensue communicate(sender, receiver, word); // FIXME Testing only //printResults(); //if (i % 100 == 0) std::cout << "Round " << i << std::endl; } // ??? (TODO) // Profit! }
/** A specialisation for bool to allow more, better values. */ bool CommandSystem::parseArgument(std::string &message, bool *result) { const static std::vector<std::string> trueValues = { "on", "true", "yes", "1" }; const static std::vector<std::string> allValues = { "on", "true", "yes", "1", "off", "false", "no", "0" }; std::vector<std::string> possible = chooseWord(allValues, message); if (possible.empty()) return false; // Look what possibilities were found bool foundTrue = false; bool foundFalse = false; for (const auto &p : possible) { if (std::find(trueValues.cbegin(), trueValues.cend(), p) != trueValues.cend()) foundTrue = true; else foundFalse = true; } if (foundTrue && foundFalse) return false; *result = foundTrue; return true; }
int main(int argc, char* argv[]) { char letter = 0; // 存储用户输入的字母 char secretWord[100] = {0}; // 要猜测的单词 int *letterFound = NULL; // 布尔值的数组. 数组的每一个元素对应猜测单词的一个字母。 0 = 还没猜到此字母, 1 = 已猜到字母 int leftTimes = 7; // 剩余猜测次数 (0 = 失败) int i = 0; // 下标 long wordSize = 0; // 单词的长度(字母数目) printf("欢迎来到悬挂小人游戏!\n"); // 从词库(文件dictionary)中随机选取一个单词 if (!chooseWord(secretWord)) exit(0); // 退出游戏 // 获取单词的长度 wordSize = strlen(secretWord); letterFound = malloc(wordSize * sizeof(int)); // 动态分配数组的大小,因为我们一开始不知道单词长度 if (letterFound == NULL) exit(0); // 初始化布尔值数组,都置为0,表示还没有字母被猜到 for (i = 0 ; i < wordSize ; i++) letterFound[i] = 0; // 主while循环,如果还有猜测机会并且还没胜利,继续 while(leftTimes > 0 && !win(letterFound, wordSize)){ printf("\n\n您还剩 %d 次机会", leftTimes); printf("\n神秘单词是什么呢 ? "); /* 我们显示猜测的单词,将还没猜到的字母用*表示 例如 : *O**LE */ for (i = 0 ; i < wordSize ; i++) { if (letterFound[i]) // 如果第i+1个字母已经猜到 printf("%c", secretWord[i]); // 打印出来 else printf("*"); // 还没猜到,打印一个* } printf("\n输入一个字母 : "); letter = readCharacter(); // 如果用户输入的字母不存在于单词中 if (!researchLetter(letter, secretWord, letterFound)) { leftTimes--; // 将剩余猜测机会数减1 } } if (win(letterFound, wordSize)) printf("\n\n胜利了! 神秘单词是 : %s\n", secretWord); else printf("\n\n失败了! 神秘单词是 : %s\n", secretWord); return 0; }