// Bulls and Cows the game // CGame.cpp // #include "defines.h" #include "CGame.h" #include "CUserInput.h" #include "CPrint.h" #include #include void CGame::Init() { m_ucBulls = 0; m_ucCows = 0; m_uStepCounter = 0; m_fGameIsEnd = false; m_sLastError = L""; std::random_device r; std::default_random_engine e(r()); std::uniform_int_distribution d(0, 9); m_uGuessedNumber = new int[m_ucDigits] { 0 }; int n = 0; for (int i = 0; i < m_ucDigits; ++i) { n = d(e); if (i > 0) { while (IsEqual(m_uGuessedNumber, n, i)) { n = d(e); } } m_uGuessedNumber[i] = n; } } void CGame::Start() { CStep step; int ret = 0; while (!m_fGameIsEnd) { do { CPrint::GameHeader(); CPrint::GuessedNumber(this, IS_SHOW); CPrint::Steps(this); } while (!GetNumber(step)); m_uStepCounter++; } CPrint::GameHeader(); CPrint::GuessedNumber(this, true); CPrint::Steps(this); CPrint::GameFooter(this); } bool CGame::GetNumber(CStep step) { std::wcout << L"\t\t\t\t\t" << m_sLastError << L"\r"; std::wcout << "=>\t"; CUserInput userInput(m_ucDigits); if (userInput.Get()) { for (unsigned i = 0; i < userInput.m_vUserInput.size(); i++) { if (IsEqual(userInput.m_vUserInput, userInput.m_vUserInput.at(i), i)) { m_sLastError = strERROR_1; return false; } } } else { m_sLastError = strERROR_2_1 + std::to_wstring(m_ucDigits) + strERROR_2_2; return false; } step.StoreStepNumber(userInput.m_vUserInput); step.CheckForAnimals(m_uGuessedNumber, m_ucDigits); m_Steps.push_back(step); if (step.GetStepAnimals().first == m_ucDigits) m_fGameIsEnd = true; m_sLastError = L""; return true; } CGame::CGame() { CUserInput userInput(1); bool ok = false; do { CPrint::GameHeader(); CPrint::GameInitialQuery(); std::wcout << "=> "; if (userInput.Get()) { if ((userInput.m_vUserInput.at(0) >= 3) && (userInput.m_vUserInput.at(0) <= 5)) { m_ucDigits = userInput.m_vUserInput.at(0); ok = true; } else { userInput.m_vUserInput.clear(); } } } while (!ok); } CGame::~CGame() { delete[] m_uGuessedNumber; }