1
我的hang子手程序有問題。我需要讓玩家對每個猜測都顯示棋盤,如果答案正確,棋盤不會改變。如果答案不正確,該板將改變。我試圖做循環,以便當用戶做出6次錯誤的猜測時,最終棋盤將顯示,意味着玩家輸掉了比賽。這是到目前爲止我的代碼...正確的循環邏輯?
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
const string boardOne = " ------|\n | |\n |\n |\n |\n -------\n\n";
const string boardTwo = " ------|\n | |\n 0 |\n |\n |\n -------\n\n";
const string boardThree = " ------|\n | |\n 0 |\n | |\n |\n -------\n\n";
const string boardFour = " ------|\n | |\n 0 |\n-| |\n |\n -------\n\n";
const string boardFive = " ------|\n | |\n 0 |\n-|- |\n |\n -------\n\n";
const string boardSix = " ------|\n | |\n 0 |\n-|- |\n \\ |\n -------\n\n";
const string boardSeven = " ------|\n | |\n 0 |\n-|- |\n/ \\ |\n -------\n\n";
int main()
{
// Declarations
string fileWord;
ifstream inFile;
int wrongGuess = 0;
char letterGuess = 0;
// while loop to get the last word from file
inFile.open("hangman.dat");
while (!inFile.eof())
{
cout << fileWord << endl;
inFile >> fileWord;
}
inFile.close();
//capitalize the word to use in the game of hangman
std::transform(fileWord.begin(), fileWord.end(), fileWord.begin(), toupper);
cout << "\nWord to Guess: " << fileWord << endl;
cout << "\n" << boardOne << endl;
while (wrongGuess != 6)
{
cout << "\nEnter a letter to guess: ";
cin >> letterGuess;
letterGuess = toupper(letterGuess);
cout << "You guessed the letter: " << letterGuess << endl;
bool found = false;
for (int i = 0; i < fileWord.length(); i++)
{
if (fileWord[i] == letterGuess)
{
cout << "\n" << letterGuess << " is in the letter to guess." << endl;
found = true;
}
}
// if not found - increment wrong guesses
if (!found)
{
wrongGuess++;
cout << "\n" << letterGuess << " is not in the word to guess." << endl;
//print the board that corresponds to the wrongGuess
if (wrongGuess = 0)
cout << boardOne << endl;
if (wrongGuess = 1)
cout << boardTwo << endl;
if (wrongGuess = 2)
cout << boardThree << endl;
if (wrongGuess = 3)
cout << boardFour << endl;
if (wrongGuess = 4)
cout << boardFive << endl;
if (wrongGuess = 5)
cout << boardSix << endl;
if (wrongGuess = 6)
cout << boardSeven << endl;
}
}
cout << "\n\n";
system("pause");
return 0;
}
你做得='和'在==不等於'的'分配的如果聲明。例如'if(wrongGuess = 0)'應該是'if(wrongGuess == 0)'。 – Arite
會有更好的方式來編碼,而不是所有這些if語句? – rfallon
您可改爲爲您的電路板提供一組「字符串」。例如: 'const string board [] = {「Board 1 Content」,「Board 2 Content」,\t「Board 3 Content」,「Board 4 Content」};'。 然後打印相關的板: 'cout << board [wrongGuess] << endl;'。 這個假設'wrongGuess'不是越界。 – Arite