Triple X - Healths Value

Good day!
I am working in a project and would like to implement the number of lives(attempts to guess the numbers).
I got confused at the moment when I need to display the task condition again and enter it again FirstGuess, SecondGuess, ThirdGuess.
Then, you check for the number of lives again and compare the sum and product again…

#include <iostream>
#include <ctime>

using namespace std;

void PrintDialogs(int LevelDiffeculty)
{
    switch (LevelDiffeculty)
    {
    case 1:
        cout << "С развитием интернета-вещей, человечество все глубже уходило в сетевую форму существования.\n";
        cout << "Платежи любой материальной формы стали чем-то невообразимым. Кредитные данные КАЖДОГО человека были внутри сети.\n";
        cout << "И вот настал день когда все они стали доступны вирусу Trinity.\n\n";
        cout << "Ты  - Хенк Андерсон, написал алгоритм который сможет подобрать код доступа к самому дорогому архиву в истории.\n";
        cout << "Чтобы поулчить доступ к архиву, тебе потребуется вводить данные которые знают только создатели вируса - команда \"РАГ\". \n";
        cout << "Твой алгоритм успешно находит зависимости у трех подряд идущих цифр, тебе остается только правильно их отгадать.\n";
        cout << "Не тяни резину, Хенк! Пора браться за спасение человечества!\n";
        cout << "Когда поймешь что это за числа, вводи цифры через пробел и жми Enter.\n\n";
        break;
    case 2:
        cout << "У тебя получается! Продолжай в том же духе!" << endl;
        break;
    case 3:
        cout << "Так, дальше будет немного сложнее, не робей!" << endl;
        break;
    case 5:
        cout << "Ох и вопросики у Вас, конечно... Не сдавайся. Надежда только на тебя." << endl;
        break;
    case 6:
        cout << "Половину уже разгадали, впереди самое сложное!" << endl;
        break;
    case 8:
        cout << "Максимальная концентрация! Не ошибись при вводе!" << endl;
        break;
    case 9:
        cout << "Это предпоследний пазл, судьба всего мира в твоих руках!" << endl;
        break;
    case 10:
        cout << "Спокойствие, Хенк! Подумай несколько раз, прежде чем дать ответ." << endl;
        break;
    }
}

int ChangeHealthsValue(int &HealthsValue)
{
    if (HealthsValue > 0)
    {
        --HealthsValue;
        cout << "Данные не верны, Хенк! Попробуй еще раз. Только будь внимателней!\n\n";
        cout << "У тебя осталось " << HealthsValue << " попытки.\n\n";
        return HealthsValue;
    }
    else
    {
        cout << "У тебя не осталось попыток.";
        return HealthsValue;
    }
}

bool PlayGame(int LevelDiffeculty, int HealthsValue)
{
    PrintDialogs(LevelDiffeculty);

    const int FirstNumber = rand() % LevelDiffeculty + LevelDiffeculty;
    const int SecondNumber = rand() % LevelDiffeculty + LevelDiffeculty;
    const int ThirdNumber = rand() % LevelDiffeculty + LevelDiffeculty;

    const int SumValues = FirstNumber + SecondNumber + ThirdNumber;
    const int ProductValues = FirstNumber * SecondNumber * ThirdNumber;

    cout << "Сумма трех цифр равна: " << SumValues << endl;
    cout << "Произведение трех цифр равно: " << ProductValues << endl;

    int FirstGuess, SecondGuess, ThirdGuess;
    cin >> FirstGuess >> SecondGuess >> ThirdGuess;

    int SumGuess = FirstGuess + SecondGuess + ThirdGuess;
    int ProductGuess = FirstGuess * SecondGuess * ThirdGuess;

    if (SumValues == SumGuess && ProductValues == ProductGuess)
    {
        cout << "Данные верны. \n\n";
        return true;
    }
    else
    {
        ChangeHealthsValue(HealthsValue);  

        if (HealthsValue > 0)
        {           
            cout << "Сумма трех цифр равна: " << SumValues << endl;
            cout << "Произведение трех цифр равно: " << ProductValues << endl;
            cin >> FirstGuess >> SecondGuess >> ThirdGuess;
        }
        else
            return false;
    }
}


int main()
{
    setlocale(LC_ALL, "ru");
    srand(time(NULL));

    int LevelDiffeculty = 1;
    int MaxLevelDiffeculty = 10;
    int HealthsValue = 3;

    while (LevelDiffeculty<= MaxLevelDiffeculty)
    {
        bool bLevelComplete = PlayGame(LevelDiffeculty, HealthsValue);
        cin.clear();// Clears any errors
        cin.ignore();// Discarts the buffer

        if(bLevelComplete)
        {
            ++LevelDiffeculty;
        }
        else
        {
            cout << "Увы, но ты проиграл. Теперь весь мир погрузится в хаос.";
            return 0;
        }
    }
    return 0;
}

I hope for help in the community. Have a nice day, everyone!

Could you explain what you’re after in a bit more detail? Could you provide an example?

OK, I’ll try. Sorry for my english, I’m working on it too)
I want to implement a variable - the number of lives(attempts to guess the hidden numbers).
Let’s say I have a total of 10 difficulty levels, and there are 3 possible mistakes to find these numbers.
And if you still these “lives”(HealthsValue), then the task is cout again, the user enters new values and a program repeat the check for correctness of the newly entered values.
And only after spending three attempts(HealthsValue) the game stopped.

That’s all)))Lastest bugs fixed, now you can taste it.

#include <ctime>

using namespace std;

void PrintTask(int &SumValues, int &ProductValues)
{
    cout << "Сумма трех цифр равна: " << SumValues << endl;
    cout << "Произведение трех цифр равно: " << ProductValues << endl;
}

void PrintDialogs(int LevelDiffeculty)
{
    switch (LevelDiffeculty)
    {
    case 1:
        cout << "С развитием интернета-вещей, человечество все глубже уходило в сетевую форму существования.\n";
        cout << "Платежи любой материальной формы стали чем-то невообразимым. Кредитные данные КАЖДОГО человека были внутри сети.\n";
        cout << "И вот настал день когда все они стали доступны вирусу Trinity.\n\n";
        cout << "Ты  - Хенк Андерсон, написал алгоритм который сможет подобрать код доступа к самому дорогому архиву в истории.\n";
        cout << "Чтобы получить доступ к архиву, тебе потребуется вводить данные которые знают только создатели вируса - команда \"РАГ\". \n";
        cout << "Твой алгоритм успешно находит зависимости у трех подряд идущих цифр, тебе остается только правильно их отгадать.\n";
        cout << "Не тяни резину, Хенк! Пора браться за спасение человечества!\n";
        cout << "Когда поймешь что это за числа, вводи цифры через пробел и жми Enter.\n\n";
        break;
    case 2:
        cout << "У тебя получается! Продолжай в том же духе!" << endl;
        break;
    case 3:
        cout << "Так, дальше будет немного сложнее, не робей!" << endl;
        break;
    case 5:
        cout << "Ох и вопросики у Вас, конечно... Не сдавайся. Надежда только на тебя." << endl;
        break;
    case 6:
        cout << "Половину уже разгадали, впереди самое сложное!" << endl;
        break;
    case 8:
        cout << "Максимальная концентрация! Не ошибись при вводе!" << endl;
        break;
    case 9:
        cout << "Это предпоследний пазл, судьба всего мира в твоих руках!" << endl;
        break;
    case 10:
        cout << "Спокойствие, Хенк! Подумай несколько раз, прежде чем дать ответ." << endl;
        break;
    }
}

bool EqualityCheck(int & SumGuess, int &ProductGuess, int &SumValues, int &ProductValues)
{
    if (SumValues == SumGuess && ProductValues == ProductGuess)
        return true;
    else
        return false;
}

int ChangeHealthsValue(int &HealthsValue)
{
    if (HealthsValue == 3)
    {
        --HealthsValue;
        cout << "Данные не верны, Хенк! Попробуй еще раз. Только будь внимателней!\n\n";
        cout << "У тебя осталось " << HealthsValue << " шанса на ошибку.\n\n";
        return HealthsValue;
    }
    else if(HealthsValue == 2)
    {
        --HealthsValue;
        cout << "Данные не верны, Хенк! Попробуй еще раз. Только будь внимателней!\n\n";
        cout << "У тебя остался " << HealthsValue << " шанс на ошибку.\n\n";
        return HealthsValue;
    }
    else
    {
        --HealthsValue;
        cout << "У тебя не осталось шансов на ошибку!\n\n";
        return HealthsValue;
    }
}

bool PlayGame(int LevelDiffeculty, int &HealthsValue)
{
    PrintDialogs(LevelDiffeculty);

    int FirstNumber = rand() % LevelDiffeculty + LevelDiffeculty;
    int SecondNumber = rand() % LevelDiffeculty + LevelDiffeculty;
    int ThirdNumber = rand() % LevelDiffeculty + LevelDiffeculty;

    int SumValues = FirstNumber + SecondNumber + ThirdNumber;
    int ProductValues = FirstNumber * SecondNumber * ThirdNumber;

    PrintTask(SumValues, ProductValues);

    int FirstGuess, SecondGuess, ThirdGuess;
    cin >> FirstGuess >> SecondGuess >> ThirdGuess;

    int SumGuess = FirstGuess + SecondGuess + ThirdGuess;
    int ProductGuess = FirstGuess * SecondGuess * ThirdGuess;

    if (EqualityCheck(SumGuess, ProductGuess, SumValues, ProductValues))
    {
        cout << "Данные верны. \n\n";
        return true;
    }
    else
    {
        ChangeHealthsValue(HealthsValue);
    }

    if (HealthsValue > 0)
    {
        PrintTask(SumValues, ProductValues);
        cin >> FirstGuess >> SecondGuess >> ThirdGuess;
        int SumGuess = FirstGuess + SecondGuess + ThirdGuess;
        int ProductGuess = FirstGuess * SecondGuess * ThirdGuess;
        bool CheckFlag = EqualityCheck(SumGuess, ProductGuess, SumValues, ProductValues);

        if (CheckFlag && HealthsValue >= 0)
        {
            cout << "Данные верны. \n\n";
            return true;
        }
        else
        {
            ChangeHealthsValue(HealthsValue);
            PrintTask(SumValues, ProductValues);
            cin >> FirstGuess >> SecondGuess >> ThirdGuess;
            int SumGuess = FirstGuess + SecondGuess + ThirdGuess;
            int ProductGuess = FirstGuess * SecondGuess * ThirdGuess;
            bool CheckFlag = EqualityCheck(SumGuess, ProductGuess, SumValues, ProductValues);
            
            if (CheckFlag && HealthsValue >= 0)
            {
                cout << "Данные верны. \n\n";
                return true;
            }
            else
            {
                ChangeHealthsValue(HealthsValue);
                PrintTask(SumValues, ProductValues);
                cin >> FirstGuess >> SecondGuess >> ThirdGuess;
                int SumGuess = FirstGuess + SecondGuess + ThirdGuess;
                int ProductGuess = FirstGuess * SecondGuess * ThirdGuess;
                bool CheckFlag = EqualityCheck(SumGuess, ProductGuess, SumValues, ProductValues);

                if (CheckFlag && HealthsValue >= 0)
                {
                    cout << "Данные верны. \n\n";
                    return true;
                }
                else
                    return false;
            }
        }
    }
    else
        return false;
}

int main()
{
    setlocale(LC_ALL, "ru");
    srand(time(NULL));

    int LevelDiffeculty = 1;
    int MaxLevelDiffeculty = 10;
    int HealthsValue = 3;

    while (LevelDiffeculty <= MaxLevelDiffeculty)
    {
        bool bLevelComplete = PlayGame(LevelDiffeculty, HealthsValue);
        cin.clear();// Clears any errors
        cin.ignore();// Discarts the buffer

        if (bLevelComplete)
        {
            ++LevelDiffeculty;
        }
        else
        {
            cout << "Увы, но ты проиграл. Теперь весь мир погрузится в хаос.";
            int DontLetConsoleCloseImmediately;
            cin >> DontLetConsoleCloseImmediately;
            return 0;
        }
    }

    cout << "Ты справился Хэнк! Теперь скорее уничтож все данные, чтобы ни кто не получил их!";
    int DontLetConsoleCloseImmediately;
    cin >> DontLetConsoleCloseImmediately;
    return 0;
}```

Please use a code block when posting code. Highlight the text and press the </> button or surround the code in three backticks

```
code goes here
```


  1. PrintTask and EqualityCheck should pass the ints by value - https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#f16-for-in-parameters-pass-cheaply-copied-types-by-value-and-others-by-reference-to-const
  2. EqualityCheck can be simplified
    return SumValues == SumGuess && ProductValues == ProductGuess;
    
    Not sure if this is worth a function though.
  3. ChangeValue can be void and the logic could be simplified slightly
    int ChangeHealthsValue(int& HealthsValue)
    {
        --HealthsValue;
        switch (HealthsValue)
        {
        case 3:
            cout << "Данные не верны, Хенк!Попробуй еще раз.Только будь внимателней!\n\n";
            cout << "У тебя осталось " << HealthsValue << " шанса на ошибку.\n\n";
            break;    
        case 2:
            cout << "Данные не верны, Хенк!Попробуй еще раз.Только будь внимателней!\n\n";
            cout << "У тебя остался " << HealthsValue << " шанс на ошибку.\n\n";
            break;
        default:
            cout << "У тебя не осталось шансов на ошибку!\n\n";
            break;
        }
    }
    
  4. With that said I don’t think you actually need that. I would handle all of that logic in main.
    int HealthValue = 3;
    
    while (LevelDifficulty <= MaxLevelDifficulty && HealthValue >= 0)
    {
        // play...
        if (bLevelComplete)
        {
            ++LevelDifficulty;
        }
        else
        {
            --HealthValue;
            // messages
        }
    }
    if (HealthValue > 0)
    {
       // won
    }
    else
    {
        // lost
    }
    

Thank you, Daniel. Can you show me how I should properly overwrite the values of variables in a functions PrintTask and EqualityCheck? Without using a link.
How i understand, link - its not panacea for the syntax, but rather an extra load on the system.

Those functions don’t change what it is passed in which was my point. They can just get a copy

void PrintTask(int SumValues, int ProductValues)

Also what you are calling “link” is called a reference.

Privacy & Terms