返回值与写出的值不同

时间:2020-01-23 18:58:37

标签: c++ c++11 return

所以我一直在写一个程序,差不多完成了,但是遇到了麻烦。我是编程的初学者,因此代码编写得并不完美,我什至都不知道类。该程序包含许多波兰语内容,但我尝试翻译一些内容,因此理解上应该没有任何问题。 是的,我曾经在这里使用namespace std;,对不起,我知道这是一种不好的做法。

#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <cctype>
#include <conio.h>
#include <fstream>
#include <random>
#include <chrono>
#include <string>

using namespace std;

char startLUBwyjscie; //startORexit
char yesorno;
int mojeHP = 100, HPosmiornicy = 100, mojaEN = 100; //myHP, Octopu'sHP, myENERGY
int wyborAtaku; //choosingTheAttack
char clickO;
//char spamX; not useful now
char clickanything;
char clickanything2;
char clickanything3; //idk if 3 variables are necessary but made it in case of problems
ofstream zapisfout; //for saving smth to the file
ifstream odczytfin; //for reading-out smth from the file
string wartoscdoodczytu; //AValueToRead-out
int liniapliku = 0; //LineOfFile
char choosethelanguage;

int PowerfulPunch(); //prototypes
int KnifeThrow();
int NormalAttack();
int OctopusAttack();
int WhosNext();


unsigned ziarno_liczb_losowych = std::chrono::steady_clock::now().time_since_epoch().count(); //seed
default_random_engine silnik_liczb_losowych(ziarno_liczb_losowych); //engine



int main()
{
    cout << "Wybierz jezyk / Choose the language" << endl;
    cout << "1. Polski (bez polskich znakow) / Polish (without Polish characters)" << endl; //does not exist, a limit of characters in my post has been exceeded so I had to delete this option
    cout << "2. English / Angielski" << endl; //click 2 always
    choosethelanguage = _getch(); //choose the language

    if (choosethelanguage == '2') //English version
    {
        system("cls");


    menu: //label
        srand(time(NULL));
        cout << "DEPTH OF ABYSSAL SEA" << endl << endl;

        cout << "1. Start" << endl;
        cout << "2. Instructions" << endl;
        cout << "3. Read-out logs of the last fight" << endl;
        cout << "4. Credits" << endl;
        cout << "5. Exit" << endl;
        startLUBwyjscie = _getch(); //menu
        switch (startLUBwyjscie)
        {
        case '1': //a story and the game
        {
            system("cls");
            cout << "Do you want to pass over the exordium? Click 'X' to pass over the exordium. Click anything else to read the exordium." << endl;
            yesorno = _getch();
            if (yesorno == 'X' || yesorno == 'x') //pass over the exordium (y/n)
                goto koniecwstepu; //go to the label
            else //exordium (story)
            {
                system("cls");
                cout << "The strory begins so many years ago." << endl;
                Sleep(2500);
                cout << "You are Felix. You are nineteen years old." << endl;
                Sleep(2500);
                cout << "You were born on Malta - country situated on the Mediterraen Sea. Simply a little island." << endl;
                Sleep(2500);
                cout << "Your grandfather told you a story which was about the Atlantis." << endl;
                Sleep(2500);
                cout << "It seemed like a fairy tale, something, what doesn't even exist." << endl;
                Sleep(2500);
                cout << "It was told that the Atlantis was situated on the Arctic Ocean. It seemed to be a long way from here." << endl;
                Sleep(2500);
                cout << "But the story was told many years ago, when you were eight. Your grandfather died several years ago." << endl;
                Sleep(2500);
                cout << "It is touching, isn't it?" << endl;
                Sleep(2500);
                cout << "But even when you were growing up, you didn't stop believing in the story." << endl;
                Sleep(2500);
                cout << "You are too young to see some things. You look from the shallow perspective." << endl;
                Sleep(2500);
                cout << "You demand an adventure! You think that you are the chosen one. The chosen one to know the secret." << endl;
                Sleep(2500);
                cout << "You took every things that might be useful in case of meeting ruins of destroyed continent." << endl;
                Sleep(2500);
                cout << "But will you able to rise to the challenge?" << endl;
                Sleep(2500);
                cout << "Let's see..." << endl;
                Sleep(10000);
            koniecwstepu: //label
                system("cls");
            }

            zapisfout.open("Logs of the last fight.txt", ios::trunc); //deleting the content before next informations
            zapisfout.close(); //closing file


        //the game
            for (int i = 1; ((mojeHP <= 100 && mojeHP > 0) && (HPosmiornicy <= 100 && HPosmiornicy > 0)); i++)
            {
                if (i == 1)
                {
                    cout << "Your HP: " << mojeHP << endl;
                    cout << "Your Energy: " << mojaEN << endl << endl;
                    cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl;
                }

            blad: //label blad (błąd means error in this case but I cannot use polish characters so I named the label 'blad')

                cout << "Round " << i << endl;

                if (WhosNext() == 1)
                    cout << "Your turn" << endl << endl;
                else
                    cout << "Octopus' turn" << endl << endl;

                cout << "Available actions: " << endl;
                cout << "1. Powerful punch (-30 Energy)" << endl;
                cout << "2. Knife throw (-45 Energy)" << endl;
                cout << "3. Normal attack (+30 Energy)" << endl;
                wyborAtaku = _getch();
                cout << endl << endl;

                if (wyborAtaku == '1') // Powerful Punch
                {
                    if (mojaEN - 30 <= 0)
                    {
                        cout << "You don't have enough energy!" << endl << endl << endl; //brak energii
                        goto blad; //go to the label
                    }


                    cout << "You deal " << PowerfulPunch() << " damage to the octopus." << endl;
                    cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
                    mojeHP -= OctopusAttack();      //substract my HP
                    mojaEN -= 30;                           //substract the energy
                    HPosmiornicy -= PowerfulPunch();    //substract octpus' HP

                    if (mojeHP <= 0)
                        cout << "Your HP: 0" << endl; //showing my HP <0
                    else
                        cout << "Your HP: " << mojeHP << endl; //showing my HP >0

                    cout << "Your Energy: " << mojaEN << endl << endl; //showing my energy

                    if (mojeHP <= 0)
                        cout << "Octopu's HP: 0" << endl; //showing octopus' HP <0
                    else
                        cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0   
                }

                else if (wyborAtaku == '2') // Knife throw
                {
                    if (mojaEN - 45 <= 0)
                    {
                        cout << "You don't have enough energy!" << endl << endl << endl;
                        goto blad;
                    }

                    cout << "You deal " << KnifeThrow() << " damage to the octopus." << endl;
                    cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
                    mojeHP -= OctopusAttack();      //substract my HP
                    mojaEN -= 45;                       //substract the energy
                    HPosmiornicy -= KnifeThrow();   //substract octpus' HP

                    if (mojeHP <= 0)
                        cout << "Your HP: 0" << endl; //showing my HP <0
                    else
                        cout << "Your HP: " << mojeHP << endl; //showing my HP >0

                    cout << "Your Energy: " << mojaEN << endl << endl; //showing my energy

                    if (mojeHP <= 0)
                        cout << "Octopu's HP: 0" << endl; //showing octopus' HP <0
                    else
                        cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0

                }

                else if (wyborAtaku == '3') // Normal attack
                {
                    cout << "You deal " << NormalAttack() << " damage to the octopus." << endl;
                    cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
                    mojeHP -= OctopusAttack();      //substract my HP
                    mojaEN += 30;                           //adding the energy
                    HPosmiornicy -= NormalAttack(); //substract octpus' HP

                    if (mojeHP <= 0)
                        cout << "Your HP: 0" << endl; //showing my HP <0
                    else
                        cout << "Your HP: " << mojeHP << endl; //showing my HP >0

                    cout << "Your Energy: " << mojaEN << endl << endl;  //showing my energy

                    if (HPosmiornicy <= 0)
                        cout << "Octopus' HP: 0" << endl; //showing octopus' HP <0
                    else
                        cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0

                }

                else if ((wyborAtaku != '1' && wyborAtaku != '2' && wyborAtaku != '3') || !isdigit(wyborAtaku))
                {
                    cout << "Incorrect character!" << endl << endl << endl;
                    goto blad;
                }

                zapisfout.open("Logs of the last fight.txt", ios::app); //opening the file and actualizing date in it
                zapisfout << "Round " << i << endl;

                if (mojeHP <= 0)
                    zapisfout << "Your HP: 0" << endl; //showing my HP <0 in file
                else
                    zapisfout << "Your HP: " << mojeHP << endl; //showing my HP >0 in file

                zapisfout << "Your Energy: " << mojaEN << endl; //showing my energy in file

                if (HPosmiornicy <= 0)
                    zapisfout << "Octopus' HP: 0" << endl; //showing octopus' HP <0 in file
                else
                    zapisfout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0 in file

                zapisfout.close(); //closing the file

            }

            if ((HPosmiornicy <= 0 && WhosNext() == 1 && mojeHP <= 0) || (HPosmiornicy <= 0 && (WhosNext() == 2 || WhosNext() == 1) && mojeHP > 0))
            {
                cout << endl << endl;
                cout << "VICTORY!!!" << endl << endl;
                Sleep(2500);
                cout << "What?! It's impossible!" << endl;
                Sleep(2500);
                cout << "Some feeble human could slay that enermous creature?" << endl;
                Sleep(2500);
                cout << "I can't believe..." << endl;
                Sleep(2500);
                cout << "You had actually nothing brought from your home..." << endl;
                Sleep(2500);
                cout << "Some food and drink, diving disguise and some blunt knives..." << endl;
                Sleep(2500);
                cout << "This world is impressive and never will stop surprising me." << endl;
                Sleep(2500);
                cout << "You see how the octopus is sinking in the sand. You can take your treasure!" << endl;
                Sleep(2500);
                cout << "You deserve, to be honest." << endl;
                Sleep(2500);
                cout << "Hey, let's make it! Open it!" << endl << endl;
                Sleep(2500);
                cout << "*CLICK 'O' TO OPEN*" << endl;
            open: //label 'open'
                clickO = _getch();
                if (clickO == 'o' || clickO == 'O')
                {
                    cout << endl;
                    cout << "You made it! Wow... These are truly beatiful..." << endl;
                    Sleep(2500);
                    cout << "You are so wealthy right now..." << endl;
                    Sleep(2500);
                    cout << "Golden ingots, diamond trident and some gems..." << endl;
                    Sleep(2500);
                    cout << "Wow... I haven't seen the things like that since billions years..." << endl; //Look at your oxygen in your bottle! You are getting strangled! SWIM UP, SWIM UP!!!"<<endl<<endl; //not really important here now 
                    Sleep(2500);
                    //cout<<"*SPAM 'X' TO SWIM UP (25 to get out in 10 seconds)* "<<endl; //not really important here now 
                    cout << "It's time for you now. Congratulations." << endl << endl;
                    Sleep(2500);
                    cout << "GOOD ENDING" << endl << endl;

                    zapisfout.open("Logs of the last fight.txt", ios::app);
                    zapisfout << "GOOD ENDING" << endl; //actualizing data in the file with an ending
                    zapisfout.close(); //closing the file

                    Sleep(10000);

                }
                else
                {
                    cout << "*WRONG CHARACTER!*" << endl << endl;
                    goto open; //coming back to 'open' label
                }
            }

            else if ((HPosmiornicy <= 0 && WhosNext() == 2 && mojeHP <= 0) || (HPosmiornicy > 0 && (WhosNext() == 2 || WhosNext() == 1) && mojeHP <= 0))
            {
                cout << endl << endl;
                cout << "DEFEAT!!!" << endl << endl;

                cout << "Happened. You died. You are a ghost." << endl;
                Sleep(2500);
                cout << "Impossible?" << endl;
                Sleep(2500);
                cout << "For sure you are wondering how it happened..." << endl;
                Sleep(2500);
                cout << "For sure you are wondering where you are now..." << endl;
                Sleep(2500);
                cout << "HELLO?!" << endl;
                Sleep(2500);
                cout << "No one hears you. It is the world of the all dead beings such as people but also animals." << endl;
                Sleep(2500);
                cout << "Don't worry. You can't die here. It wouldn't be logical. But you can be vexed by other creatures living here." << endl;
                Sleep(2500);
                cout << "Now you can worry." << endl;
                Sleep(2500);
                cout << "What happened to the octopus, you probably wonder." << endl;
                Sleep(2500);
                cout << "It is still alive and it is waiting for other daredevils that will think that they are, as you named it, 'the chosen ones'. Funny cycle, isn't it?" << endl;
                Sleep(2500);
                cout << "Sorry, you didn't manage to slay the creature." << endl;
                Sleep(2500);
                cout << "You were too weak." << endl;
                Sleep(2500);
                cout << "Oh look! Something approaches to you! Looks known..." << endl;
                Sleep(2500);
                cout << "-I said that the Atlantis had existed..." << endl << endl;
                Sleep(2500);
                cout << "BAD ENDING" << endl << endl;

                zapisfout.open("Logs of the last fight.txt", ios::app);
                zapisfout << "BAD ENDING" << endl; //actualizing data in the file with an ending
                zapisfout.close(); //closing the file

                Sleep(10000);
            }


            break;
        }
        case '2': //just explaining the game
        {
            system("cls");
            cout << "You start the game in menu. There you can choose an option:" << endl;
            cout << "1. Start, if you want to start the game." << endl;
            cout << "2. Instructions, if you want to know how to play the game, the place where you are now." << endl;
            cout << "3. Read-out logs of the last fight to see the course of the latest battle." << endl;
            cout << "4. Exit, if you want to go out of the game." << endl << endl;
            cout << "After clicking Start you are going to see the exordium which you can pass over by clicking 'x'." << endl;
            cout << "The exordium brings you into the main story." << endl;
            cout << "In game, you have three bars:" << endl;
            cout << "Your HP" << endl;
            cout << "Your Energy" << endl;
            cout << "Octopus' HP" << endl;
            cout << "The bars show the level of your health points, your energy points and octopus' health points." << endl;
            cout << "Your HP goes down when octopus attacks you." << endl;
            cout << "Your energy is spent by using your abilities." << endl;
            cout << "Octopus' HP goes down when you attack it." << endl;
            cout << "All abilities always deal damage, there cannot be a situation when the skills deal 0 damage." << endl;
            cout << "All values on the start are equal 100." << endl;
            cout << "Every dealt damage is generated by random numbers or psuedorandom numbers. It all depends of RNG god." << endl;
            cout << "Your character has 3 spells: " << endl;
            cout << "1. Powerful Punch" << endl;
            cout << "This spell uses 30 of your energy and deals 20-35 damage." << endl;
            cout << "2. Knife Throw" << endl;
            cout << "This spell uses 45 of your energy and deals 36-50 damage." << endl;
            cout << "3. Normal Attack" << endl;
            cout << "This spell gives you 30 energy and deals 1-15 damage." << endl;
            cout << "The octopus doesn't have any special attacks but it always deals damage 1-50 damage." << endl;
            cout << "As it was told, octopus doesn't have any special attacks, so it doesn't have energy points too." << endl;
            cout << "The battle is split on rounds." << endl;
            cout << "Every round is began by the octopus or by you, all depends of drawn order." << endl;
            cout << "If Your HP and Octopus' HP are equal 0, then drawn order decides about victory and defeat." << endl << endl;
            cout << "CLICK ANYTHING TO EXIT THE ISTRUCTIONS AND REGAIN TO THE MAIN MENU" << endl;

            clickanything = _getch();

            if (clickanything)
            {
                cout << "You will be brought to the main menu in a moment." << endl;
                Sleep(2500);
                system("cls");
                goto menu; //going to the 'menu' label          
            }

            break;

        }
        case '3': //file
        {
            system("cls");
            odczytfin.open("Logs of the last fight.txt"); //opening the file

            if (!odczytfin.is_open())
            {
                cout << "It was not able to open the file! You will be brought to the main menu in a moment." << endl;
                Sleep(2500);
                system("cls");
                goto menu; //going to the 'menu' label
            }


            while (odczytfin.good()) //checking if the file is okay
            {
                liniapliku++;
                getline(odczytfin, wartoscdoodczytu);
                cout << wartoscdoodczytu << endl;
            }


            if (odczytfin.eof()) //if eof(), click anything
            {
                cout << endl << endl;
                cout << "CLICK ANYTHING TO EXIT THE LOGS AND REGAIN TO THE MAIN MENU" << endl;

                clickanything2 = _getch();

                if (clickanything2)
                {
                    cout << "You will be brought to the main menu in a moment." << endl;
                    Sleep(2500);
                    system("cls");
                    goto menu; //going to the 'menu' label          
                }

            }
            odczytfin.close(); //closing the file
        }

        case '4': //credits
        {
            system("cls");
            cout << "The game was whole made by Vatnax. (and the guys who helped me with a problem)" << endl << endl;
            cout << "CLICK ANYTHING TO EXIT THE CREDITS AND REGAIN TO THE MAIN MENU" << endl;

            clickanything3 = _getch();
            if (clickanything3)
            {
                Sleep(2500);
                system("cls");
                goto menu; //going to the 'menu' label
                break;
            }
        }
        case '5': //exit
        {
            exit(0);
            break;
        }
        default: //if input wrong value in a menu
        {
            cout << "Incorrect value! You will be brought to the main menu in a moment." << endl;
            Sleep(2500);
            system("cls");
            goto menu; //going to the 'menu' label
            break;
        }

        }

    }
}
//functions
int PowerfulPunch()
{
    uniform_int_distribution<int> dystrybutor_liczb_losowych(20, 35); //distributor of a random number
    return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}

int KnifeThrow()
{
    uniform_int_distribution<int> dystrybutor_liczb_losowych(36, 50); //distributor of a random number
    return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}

int NormalAttack()
{
    uniform_int_distribution<int> dystrybutor_liczb_losowych(1, 15); //distributor of a random number
    return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}

int OctopusAttack()
{
    uniform_int_distribution<int> dystrybutor_liczb_losowych(1, 50); //distributor of a random number
    return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}

int WhosNext() //responsible for who starts the round
{
    uniform_int_distribution<int> dystrybutor_liczb_losowych(1, 2); //distributor of a random number
    return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}

这是长代码,但其中一半是程序的波兰语版本。 问题是,从函数返回的值稍后会从当前mojeHP变量状态中减去。其后显示mojeHP,但没有应有的值。都是在146-162、173-189、195-211行中制作的。

我复制了整个代码,因为我什至不知道问题出在哪里,所以也许将需要所有代码,而不仅仅是其中的一部分。

例如:

您的HP:100

您的能量:100

章鱼的生命值:100

第一回合

轮到你了

可用的操作:

  1. 强力拳(-30能量)

  2. 掷刀(-45能量)

  3. 普通攻击(+30能量)

您对章鱼造成15点伤害。 章鱼对您造成12点伤害。

您的HP:66 // 100-12不等于66

您的能量:130 // //应该这样写出来,因为在这种情况下总是添加30能量

章鱼的HP:91 // 100-15不等于91

1 个答案:

答案 0 :(得分:0)

相关代码似乎是:

cout << "You deal " << NormalAttack() << " damage to the octopus." << endl;
cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
mojeHP -= OctopusAttack();      //substract my HP
mojaEN += 30;                           //adding the energy
HPosmiornicy -= NormalAttack(); //substract octpus' HP

每次调用NormalAttack()时都会生成一个新的随机数。当您两次调用它时,您会得到2个数字,打印一个,然后使用另一个更新生命值。您的代码应为:

auto myAttack = NormalAttack();
auto enemyAttack = OctopusAttack();
cout << "You deal " << myAttack << " damage to the octopus." << endl;
cout << "The octopus deals you " << enemyAttack  << " damage." << endl << endl << endl;
mojeHP -= enemyAttack;      //substract my HP
mojaEN += 30;                           //adding the energy
HPosmiornicy -= myAttack; //substract octpus' HP

不需要每种语言的代码副本,只需将所有语言字符串放入数组或映射中,然后选择用于更改语言的数组即可(对于真正的项目,请使用国际化框架) 。例如像这样的东西:

std::map<std::string, std::string> english =
{ 
  { "hello", "Hello" },
  { "goodbye", "Goodbye" },
};

std::map<std::string, std::string> polish =
{ 
  { "hello", "Witaj" },
  { "goodbye", "Do widzenia" },
};

auto& language = choosethelanguage == '2' ? english : polish;

std::cout << language["hello"] << "\n";
std::cout << language["goodbye"] << "\n";

您可能希望将字符串查找包装到一个函数中以检查无效值,然后返回键,而不是返回上面代码中产生的空字符串。