mirror of
https://gitflic.ru/project/w0lf/bulls-and-cows-cpp.git
synced 2026-03-28 16:02:46 +03:00
130 lines
2.1 KiB
C++
130 lines
2.1 KiB
C++
// Bulls and Cows the game
|
|
// CGame.cpp
|
|
//
|
|
#include "defines.h"
|
|
#include "CGame.h"
|
|
#include "CUserInput.h"
|
|
#include "CPrint.h"
|
|
#include <iostream>
|
|
#include <random>
|
|
|
|
void CGame::Init()
|
|
{
|
|
m_nBulls = 0;
|
|
m_nCows = 0;
|
|
m_nStepCounter = 0;
|
|
m_fGameIsEnd = false;
|
|
m_sLastError = L"";
|
|
|
|
std::random_device r;
|
|
std::default_random_engine e(r());
|
|
std::uniform_int_distribution<int> d(0, 9);
|
|
|
|
m_nGuessedNumber = new int[m_nDigits] { 0 };
|
|
|
|
int n = 0;
|
|
|
|
for (int i = 0; i < m_nDigits; ++i)
|
|
{
|
|
n = d(e);
|
|
if (i > 0)
|
|
{
|
|
while (IsEqual(m_nGuessedNumber, n, i))
|
|
{
|
|
n = d(e);
|
|
}
|
|
}
|
|
m_nGuessedNumber[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_nStepCounter++;
|
|
}
|
|
|
|
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_nDigits);
|
|
|
|
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_nDigits) + strERROR_2_2;
|
|
return false;
|
|
}
|
|
|
|
step.StoreStepNumber(userInput.m_vUserInput);
|
|
step.CheckForAnimals(m_nGuessedNumber, m_nDigits);
|
|
m_vSteps.push_back(step);
|
|
|
|
if (step.GetStepAnimals().first == m_nDigits) 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_nDigits = userInput.m_vUserInput.at(0);
|
|
ok = true;
|
|
}
|
|
else
|
|
{
|
|
userInput.m_vUserInput.clear();
|
|
}
|
|
}
|
|
} while (!ok);
|
|
}
|
|
|
|
CGame::~CGame()
|
|
{
|
|
delete[] m_nGuessedNumber;
|
|
}
|