rand number inclining. (C++) [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Problems with srand(), C++
Basically, the random number I am generating is inclining in size, everytime it is used inside my while loop. It being random, should't incline and not be random as such.
The variable hit is defined by the random number. But as I said, the random number is not random. Also, as the random number gets bigger it goes over the limit I set for it.
//Code im using for random number :
srand((unsigned)time(0));
hit = rand()%15;
//The subject for the problem :
while (1) {
if (mon1==0) {
cout << "A dragon appears." << endl;
system ("pause");
cout << "Enter 1 to attack and 2 to run away, " <<name << endl;
cin >> act;
if (act==2) {
cout << "You run away. " << endl;
}
if (act==1) {
cout << " You choose to attack! Good luck " << endl;
}
}
if (mon1==1) { // orc
srand((unsigned)time(0));
hit = rand()%15;
ehealth = (100);
cout << " A orc appears" << endl;
system ("pause");
cout << "Enter 1 to attack and 2 to run away, " <<name << endl;
cin >> act;
system ("cls");
if (act==2) {
cout << "You run away. " << endl;
system ("cls");
}
if (act==1) { // ATTACK HERE MAIN ATTACk TESING !!!!!!!!!!!!!!!!!!!!!!! ORC
cout << " You choose to attack! Good luck " << endl;
cout << " Your health is " << health << endl;
cout << " The enemys health is " << ehealth << endl;
cout << " You have 3 abilitys." << endl;
while (1) {
cout << " Press 1 to swipe, 2 to block the enemys attack and 3 to use your special attack" <<endl;
cin >> act1;
system ("cls");
if (act1==1) {
cout << " You swipe the enemy " << endl; // swipe
cout << " You hit for " << hit << endl;
if (wep==1) {
hit = (hit + 4);
cout << " As you are the axe i will add on 4 to that, making " << hit << endl; // axe
}
ehealth = (ehealth - hit);
cout << " The enemys health is " << ehealth << endl;
cout << " Your health is " << health << endl;
system ("pause");
}
if (act1==2) {
cout <<" You block, making you immune to the next attack" << endl; //block
ehit = (0);
//newrand
cout << " Your health is " << health << endl;
cout << " The enemys health is " << ehealth << endl;
}
if (act1==3) {
cout << " Special attack is being worked on BUDDY, GUY, FRIEND!! " << endl;
}
system ("pause");
if (health < 0) {
cout << "You died, sorry!" << endl;
}
if (ehealth < 0) {
cout << " Yay! You killed the enemy!" << endl;
}
if (health == 0) {
cout << "You died, sorry!" << endl;
}
if (ehealth == 0) {
cout << " Yay! You killed the enemy!" << endl;
}
cout << " Now it is the enemys turn! " << endl;
health = ( health - ehit );
cout << " The enemy hits you for a " << ehit << endl;
cout << " Your health is now " << health << endl;
srand((unsigned)time(0));
ehit = rand()%10;
system ("pause");
system ("cls");
}
// END OF ORC
}
}

hit is randomized when the program starts.
If the monster is an orc, hit is re-randomized.
Every time you attach with an axe, hit permanently increases by four.
You probably want to re-randomize hit each time the user attacks as well?

This code causes this behavior:
hit = (hit + 4);
You increase hit always by 4. So you should use a temporary variable instead.

You only need to call srand once, at the start of the program. That "seeds" the random number generator for an unlimited number of rand() calls afterwards - calling it multiple times will just make the random numbers not random, as you encountered.

Related

How do I store 1 INT into another or have it stored somewhere so it updates every time the script finishes?

My script is below for a project I'm working on as I learn/practice.
I'd like to know how to keep track of the health. It seems, currently I'm just adding/subtracting/keeping it the same but the system has no no where to actually record the health and I'm not sure how to do it.
Also, what am I doing wrong as I tried to make the script repeat once it's finished but instead, it gives me a blank space instead of giving the Attack/Defend/Heal options again.
I tried the "do" + "while" conditions so DO this script WHILE the health is above 0 ---it works (kind of). The script doesn't end which is an improvement BUT it doesn't repeat the Attack/Defend/Heal menu.
#include <iostream>
using namespace std;
int main() {
int health = 50;
int Attack = 1;
int Defend = 2;
int Heal = 3;
do {
std::cout << "Please select an option: " << endl;
std::cout << "1. Attack" << endl;
std::cout << "2. Defend" << endl;
std::cout << "3. Heal" << endl;
int Move;
std::cin >> Move;
if (Move == 1) {
std::cout << "You did 1 damage" << endl;
std::cout << "You lost 1 health" << endl;
// while (health - 1)
std: cout << "Your current health is: " << health -1 << endl;
while (health > 0);
}
if (Move == 2) {
std::cout << "You took no damage" << endl;
std::cout << "You lost 0 health" << endl;
cout << "Your current health is: " << health << endl;
}
if (Move == 3) {
std::cout << "You gained 1 health" << endl;
cout << "Your current health is: " << health +1 << endl;
}
}
while (health > 0);
}
Remove the first while (health > 0);, that what's called an infinite loop and that is what is giving you the 'blank space'.
The second while (health > 0); is fine because that is the last part of the do .. while loop.
Secondly to store the new health you have to use the health variable. You must assign the new value to this variable, just like you assigned the initial value of 50. E.g.
// assign new health value
health = health - 1;
// display new health value
std::cout << "Your current health is: " << health << std::endl;

sleep or time delay for C++ Program

So I'm writing this spinoff game of Paperboy as a class project. If I wanted to I could say I'm finished and turn it in but I want it to have a professional touch to it. My game consists of different modes: easy and hard. However I have not implemented the hard mode yet.
Anyway, here is my code
void easyMode() {
string playerName;
int numNewspapers, numDelivered = 0, numMissed = 0, score = 0;
cout << "Enter Your Player Name: ";
cin >> playerName;
cout << "\nEnter How Many Newspapers That Need To Be Delivered: ";
cin >> numNewspapers;
cout << "\n\nYou have " << numNewspapers << " newspapers to deliver!\n\n";
cout << "Time To Deliver !!\n\n";
cout << "*===================================*\n\n";
//cout << string(50, '\n');
while (numDelivered < numNewspapers) {
int outcome = RandomNumberEasy();
cout << "*===================================*\n\n";
cout << "Delivering Newspaper...\n\n";
// Game Sequence
//*===================================*
// Delivered Successfully
//*===================================*
if (outcome <= 3 || outcome > 7) {
cout << "You Successfully Delivered The Newspaper.\n\n";
numDelivered++;
score = score + 15;
cout << "Your score is " << score << " points!\n\n";
}
// Delivery Failed
//*===================================*
else {
cout << "The Neighbor's Dog Chased You. Delivered Paper Didn't Quite Land On Step\n\n";
numDelivered++;
numMissed++;
score = score + 5;
cout << "Your score is " << score << " points!\n";
}
cout << "\n";
sleep(1);
}
// END GAME
//*===================================*
if (numDelivered == numNewspapers) {
int SuccDeliver = numDelivered - numMissed;
cout << "*===================================*\n\n";
cout << "Congratulations, " << playerName << "!\n\n";
cout << "Your Final Score Is: " << score;
cout << "\n\nYou missed " << numMissed << " Newspapers And Delivered " << SuccDeliver << " Newspapers\n\n";
}
}
As you can see I do have the sleep function in there, but when I run my program, it waits a long time and the outputs every iteration all at once. I want it to wait in between each iteration but I can't seem to get it to work.
Any help is appreciated!
The problem seems to be that the output buffer is not being flushed. A way to do it is to use cout << endl instead of cout << "\n". Mainly, this part:
cout << "\n";
sleep(1);
Should be like this:
cout << endl;
sleep(1);
And that should fix it!

Selecting an array value using a random number generator

its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.

Returned values are not the same as written out

So I've been writing a program and it's almost done but I met with a trouble. I am a beginner in programming so the code is not written perfectly, I don't even know classes. The program has many Polish things but I tried to translate some so there should not be any problem with understanding.
And yes, I used using namespace std; here, I know it is a bad practise, sorry.
#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
}
It's the long code, but half of this is a Polish version of the program.
The problem is that the values returned from functions are subtracted later from current mojeHP variable state. After it, mojeHP is shown but it doesn't have the value as it should have. It is all made in the lines 146-162, 173-189, 195-211.
I copied the whole code because I don't even know where the problem is so maybe all the code will be needed, not only a piece of it.
E.g.:
Your HP: 100
Your Energy: 100
Octopus' HP: 100
Round 1
Your turn
Available actions:
Powerful punch (-30 Energy)
Knife throw (-45 Energy)
Normal attack (+30 Energy)
You deal 15 damage to the octopus.
The octopus deals you 12 damage.
Your HP: 66 // 100 - 12 is not equal 66
Your Energy: 130 // this one is written out as it should have been because there is always added 30 energy in this case
Octopus' HP: 91 // 100 - 15 is not equal 91
The relevant code seems to be:
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
Each time you call NormalAttack() a new random number is generated. As you are calling it twice you get 2 numbers, print one and use the other to update the hit points. Your code should be:
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
There is no need to have a copies of your code for each language, just put all your language strings in an array or map and choose which array to use to change the language (or for a real project use an internationalisation framework). e.g. something like this:
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";
You'd probably want to wrap the string lookup into a function to check for invalid values and return back the key instead of the empty string that would result from the above code.

How to receive key input without requiring ENTER? [duplicate]

This question already has answers here:
C++ cin keypress event
(4 answers)
Capture characters from standard input without waiting for enter to be pressed
(21 answers)
Closed 8 years ago.
i=0;
while(i<=20)
{
nullchoice:
system("CLS");
//Advanced Information
cout << "Your Statistics: " << endl;
cout << endl << endl;
cout << " 1 Strength: " << str << endl;
cout << endl;
cout << " 2 Vitality: " << vit << endl;
cout << endl;
cout << " 3 Agility: " << agi << endl;
cout << endl;
cout << " 4 Thaumaturgy: " << tha << endl;
cout << endl << endl;
cout << "Points Remaining: " << lvlskills << endl;
cout << endl;
cout << "Enter the number of the skill you wish to increase: ";
//Applying points to skill attributes
if(i<=19)
{
cin >> input;
if(input==1)
str+=1;
else if(input==2)
vit+=1;
else if(input==3)
agi+=1;
else if(input==4)
tha+=1;
else
goto nullchoice;
lvlskills-=1;
}
i++;
cout << endl << endl;
}
So essentially, I am creating a game in C++, a text-based RPG. It's fairly basic, with stats (Strength, Vitality, etc.) you might expect from such a game. In the beginning, as shown here, the player is allowed to distribute some points to skills they choose.
Here's where the problem arises. Right now, the player must enter a number (1, 2, 3, or 4. If it's none of these numbers it will goto the nullchoice), then press ENTER. It's unwieldy and just plain wrong to have the player do this, so is there any simple way that I can code it so they only have to press the number?
I'd imagine I would use this very much throughout the rest of my game. Thanks for reading!
You just need to store the input and compare it to the required case. Put a think on it...
do
{
system("CLS");
//Advanced Information
cout << "Your Statistics: " << endl;
cout << endl << endl;
cout << " 1 Strength: " << str << endl;
cout << endl;
cout << " 2 Vitality: " << vit << endl;
cout << endl;
cout << " 3 Agility: " << agi << endl;
cout << endl;
cout << " 4 Thaumaturgy: " << tha << endl;
cout << endl << endl;
cout << "Points Remaining: " << lvlskills << endl;
cout << endl;
cout << "Enter the number of the skill you wish to increase: ";
//Applying points to skill attributes
char input;
switch(input=getch()){
case '1':
str+=1;
lvlskills-=1;
break;
case '2':
vit+=1;
lvlskills-=1;
break;
case '3':
agi+=1;
lvlskills-=1;
break;
case '4':
tha+=1;
lvlskills-=1;
}
cout << endl << endl;
} while(lvlskills>0);
Avoid goto in your code while you can solve it by other options. It's a good practice..