I am trying to practice my C++ in order to grasp a better understanding in class, as I am a beginner and a little behind, and I came across a zombie game that someone posted online.
Anyways, I understand most of the code, however I do not understand "if(rand() & 67 < 10)".
I can interpret "rand() % 10 + 1", in which the code will generate a number, or in this case zombies, between 1 and 10.
Thinking at first that the zombies would cap at 67, given the player had chosen a high number, but I don't believe that is its function, but again, I'm not entirely sure...
Here is an example of the code I am looking at:
I'm sure its something simple, however I am still confused on its purpose. Even after trying to learn its function my running the game
Here is the whole code just in case:
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int createZombie() { // createZombie function OPEN
if(rand() % 67 < 10)
return 11;
else
return rand() % 10 + 1;
} // createZombie fuction CLOSED
// #################### MAIN FUNCTION ############################
int main() { // main function OPEN
srand(time(NULL));
char enter;
// game stats
int playerAlive = true;
int playerSkill = 9;
int playerScore = 1;
string playerName = "";
int zombieCount = 0;
int zombiesKILLed = 0;
// title
cout << "Welcome to Zombie War." << endl << "Press [ENTER] to start ";
cin.get();
// player name
cout << "Please enter your name: ";
cin >> playerName;
// ask how many zombies
cout << "How many zombies do you wish to fight? ";
cin >> zombieCount;
cout <<"Get ready to fight for you life, " << playerName << "!" << endl;
// main game loop
while(playerAlive && zombiesKILLed < zombieCount) { // while loop OPEN
// create a random zombie
int zombieSkill = createZombie();
// battle sequence
if(zombieSkill > 10) { // if statment OPEN
cout << endl << "Here comes a huge zombie! " << endl;
} // if statement CLOSED
else { // else statement OPEN
cout << endl << "Here comes Zombie " << zombiesKILLed + 1 << endl;
} // else statement CLOSED
cout << "Fighting... " << endl;
sleep(2);
// zombies killed the player
if(playerSkill < zombieSkill) { // if statement OPEN
playerAlive = false;
cout << "You have died." << endl;
} // if statement CLOSED
else { // else statment OPEN
// PLAYER KILLED THE ZOMBIE
if(playerSkill - zombieSkill > 7) { // if statement OPEN
cout << "You wasted the Zombie! " << endl;
playerScore = playerScore * 2;
} // if statment CLOSED
else if (playerSkill - zombieSkill > 5) { // else if statement OPEN
cout << "You decapitated the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statement CLOSED
else if (playerSkill - zombieSkill > 0) { // else
if statement OPEN
cout << "You Killed the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statment CLOSED
else { // else statment OPEN
cout << "You killed the zombie, but suffered injuries." << endl;
} // else statment CLOSED
zombiesKILLed++;
} // else statment CLOSE
cout << endl;
sleep(1);
} // while loop CLOSED
if(zombiesKILLed == zombieCount) { // if statement OPEN
// victory
cout <<"Your have survived the onslaught!" << endl;
} // if statement CLOSED
else { // else statement OPEN
// LOST
cout << "You did not survive the zombie war" << endl;
} // else statement CLOSED
cout << "Zombies killed: " << zombiesKILLed << endl;
cout << "Final score: " << playerScore << endl << endl;
} // main function CLOSED
Splitting the command into two parts for easy understanding:
Part I-
rand() % 67
= generate any random number from 0-66
= remainder of division of any number by 67
= N (say)
Part II
if( rand() % 67 < 10)
= if( N < 10)
Related
My program will repeat output: "You are currently on the 2 floor out of 5
The sum of the codes is: 7 and the product of the codes is: 12
Try again before he catches onto you!"
Based on how many wrong characters are added how can I fix this? I have inserted the cin.clear and cin.ignore but it will repeat the part above.
i.e. if I type wasds it will repeat 5x. Any other notes are also appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int PlayerLevel = 0;
int MaxLevel = 5;
bool GamePlay ()
{
srand(time(NULL));
int PlayerGuessA, PlayerGuessB, PlayerGuessC;
int CodeA = rand() % PlayerLevel + PlayerLevel;
int CodeB = rand() % PlayerLevel + PlayerLevel;
int CodeC = rand() % PlayerLevel + PlayerLevel;
int SumofCodes = CodeA + CodeB + CodeC;
int ProductofCodes = CodeA * CodeB * CodeC;
cout << "You are currently on the " << PlayerLevel << " floor out of 5" << endl;
cout << "The sum of the codes is: " << SumofCodes << " and the product of the codes is: " << ProductofCodes << endl;
cin >> PlayerGuessA >> PlayerGuessB >> PlayerGuessC;
int PlayerProduct = PlayerGuessA * PlayerGuessB * PlayerGuessC;
int PlayerSum = PlayerGuessA + PlayerGuessB + PlayerGuessC;
if (PlayerProduct == ProductofCodes && SumofCodes == PlayerSum) {
cout << "Great Job you got this!!!\n" << endl;
++PlayerLevel;
return true;
}
else
{
cout << "Try again before he catches onto you!\n" << endl;
return false;
}
}
int GameStart()
{
string Introduction = "Welcome to your worst nightmare. You are trapped in a murderer's house. You are on the 5th floor and need to get to the first floor to escape.\n";
string Instructions = "He has each door locked behind a security system that requires a 3 number code to disarm it.\nEnter the codes and move foward. Each level will the code will be harder to figure out.\n";
string PlayerStart;
cout << Introduction << endl;
cout << Instructions << endl;
cout << "Would you like to escape? Yes or No" << endl;
cin >> PlayerStart;
if (!(PlayerStart != "Yes" && PlayerStart != "yes")) {
++PlayerLevel;
}
return 0;
}
int main ()
{
if (PlayerLevel == 0) {
GameStart();
}
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
cin.clear ();
cin.ignore();
}
cout << "You Made it out! Now run before he finds out!" << endl;
return 0;
}
When the type of the input doesn't match the type of the variable that it is being extracted to, cin sets the fail bit. Once this happens, all subsequent reads fail until the stream is reset. The offending characters are still left in the buffer, so that needs to be cleared out as well.
Your usage of cin.clear() and cin.ignore() meant that the fail bit was getting reset, but only one offending character was being removed (cin.ignore() ignores one character by default). This is why you saw the output repeating x times for x erroneous characters.
You could do something like this:
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
if (cin.fail())
{
//Input extraction failed, need to reset stream and clear buffer until newline
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
}
I'm trying to learn C++, my first idea was to make simple win/lost ratio calculator, but it's not working well.
This is my code:
#include<iostream>
#include<conio.h>
using namespace std;
int match=0;
int win=0;
int lose=0;
int ratioo=1;
int total=0;
void lost()
{
if (match=='L');
lose=lose+1;
}
void won()
{
if (match=='W');
win=win+1;
}
int main() {
cout << "Welcome to winratio calculator!" << endl;
cout << "Pressing W adds one win point" << endl;
cout << "Pressing L adds one lose point" << endl;
cout << "Press ENTER to start" << endl;
cout << "Press ESC to close" << endl;
getch();
while(1)
{
cout << "Last game score: ";
cin >> match;
total++;
won();
lost();
ratioo=(win/total)*100;
cout << "Games won: " << win << endl;
cout << "Games lost: " << lose << endl;
cout << "Ratio: " << ratioo <<"%" << endl;
break;
}
return 0;
}
And now my problems:
1)After pressing ANY key there is +1 to win and lose same time
2)I got no idea how to start whole calculator with ENTER and stop it by ESC by getch();, tried few ways but always some errors on the way(it should add points all the time until ESC is pressed
Explanations are very welcome!
Okay, so it looks like we've got a couple of errors in your program as it is now. Let's take a look!
First thing's first. Notice that you have Semicolons at the end of your if statements.
void lost()
{
if (match=='L'); //NOTE: This is a useless if statement
lose=lose+1; //As is, this line will ALWAYS RUN regardless of what character is pressed.
}
void won()
{
if (match=='W'); //Same as Above ^^^^^
win=win+1;
}
Remember that in C, the if statement will execute the next statement conditionally. Remember also that a ; in C is a statement. So, by adding a semicolon after an if statement, you're nullifying the if conditional because the if statement will run the semicolon conditionally, and not your lose = lose + 1;.
Consider writing this instead:
void lost()
{
if (match == 'L')
{
lose = lose + 1;
}
}
void won()
{
if (match == 'W')
{
win = win + 1;
}
}
Furthermore, I noticed that you've inserted a break command to avoid an infinite while(1) loop. To avoid this problem. Consider using match = _getch() instead of cin << match.
match = _getch();
In addition, your Ratioo variable is not receiving anything but 0 due to truncation. To get the percentage you're looking for, you must cast your win/total to double as follows:
ratioo = ((double)win / (double)total) * 100;
So, Now we get to detecting the ESC And ENTER Keys! This is exciting. So, in order to read in these invisible characters, you have to understand that to the computer, these keys are just numbers. The ESC Key is number 27, and the ENTER Key is number 13 (Look Up the ASCII Table for a full list). So To detect them you need to do the following:
match = _getch();
if (match == 27) //27 is the ASCII Code for the Escape Key
{
break;
}
OR Just Substitute 13 if you're looking for the Enter key. By adding A while(1) Loop around it, you can pause a program until that key is pressed (AND ignore all other input).
My Final Version of your Code can be viewed below:
#include<iostream>
#include<conio.h>
using namespace std;
int match = 0;
int win = 0;
int lose = 0;
int ratioo = 1;
int total = 0;
void lost()
{
if (match == 'L')
{
lose = lose + 1;
}
}
void won()
{
if (match == 'W')
{
win = win + 1;
}
}
int main() {
cout << "Welcome to winratio calculator!" << endl;
cout << "Pressing W adds one win point" << endl;
cout << "Pressing L adds one lose point" << endl;
cout << "Press ENTER to start" << endl;
cout << "Press ESC to close" << endl;
while (1)
{
match = _getch();
if (match == 13) //13 is the ASCII Code for the Enter Key
{
break;
}
}
while (1)
{
cout << "Last game score: ";
match = _getch();
if (match == 27) //27 is the ASCII Code for the Escape Key
{
break;
}
total++;
won();
lost();
ratioo = ((double)win / (double)total) * 100;
cout << "Games won: " << win << endl;
cout << "Games lost: " << lose << endl;
cout << "Ratio: " << ratioo << "%" << endl;
}
return 0;
}
Enjoy! And I wish you well towards learning C!
So, I'm super new to C++ and am sharing a book with a friend. I'm creating a simple guessing game, where the user imagines a number, and the computer attempts to guess it. When I debug in Visual Studio, the project does make a guess, and properly prints "how did I do?". At this point, it should get user input for the 'feedback' variable. After the prompt, however, it seems as if it will only repeat everything before the 'while' statement. Does the problem concern the feedback char variable (maybe I should've just used 'cin' and integers?), or am I just missing something really obvious?
//Game that attempts to guess a number from one to twenty.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback[1];
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << endl << endl;
cout << " Waiting on you..." << endl << " ";
cin.get();
while(gamecont)
{
cout << " I'm thinking your number is " << guess << "." << endl << endl;
cout << " How did I do?" << endl << endl << " ";
cin.get(feedback, 1);
if (feedback[1] == 1) // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback[1] == 2) // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback[1] == 3) // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
Sorry if this question is stupid for whatever reason, and thanks in advance for reading.
a journey of a thousand miles begins with a single step, so here´s some aid for your first step:
using namespace std;
don´t do that. std:: is crowded with identifiers you might use too, problems are guaranteed.
char feedback[1];
You´ll never have input longer than 1, so
char feedback;
is more than appropriate. (besides: arrays are 0 based so it should have been char feedback[0]; instead of char feedback[1];)
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
std::endl flushes the buffer, no need to do that twice. Simply use '\n':
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
you´ll get the character code of the key in feedback. '1' is not equal to 1, so
if (feedback == 1)
should be
if (feedback == '1')
Thats it. There still some work remaining to do for you, e.g. the guessing strategy is poor, but that should be a start.
//Game that attempts to guess a number from one to twenty.
#include <iostream>
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback;
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
std::cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << "\n\n";
std::cout << " Waiting on you..." << "\n\n";
std::cin.get();
while(gamecont)
{
std::cout << " I'm thinking your number is " << guess << "." << "\n\n";
std::cout << " How did I do?" << "\n\n";
std::cin.ignore();
std::cin.get(feedback);
if (feedback == '1') // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback == '2') // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback == '3') // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
I am facing difficulties in my C++ code. I am a beginner. Like, only with very basic knowledge of C++. So, I really can't figure a way to do this. I thought of making an RPG game using C++ commands and am close to finishing it. But somehow, I couldn't make a constant health for the hero. Taking a look at the code,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
As you see, I have called for battle(abc) and battle(hero.health) [which I have commented for now] but the problem is, it says "Too many arguments to function int battle(). Previously, I simply avoided parameters and created object "hero" in the battle method itself. But every time you get through a battle sequence, it comes back and declares it again, thus making its health refill. [Look at if (hero.health > 0) ]
I really don't know about global variables and all that. I just want to know if there is a workaround or a way to solve this parameter problem. Any other suggestions to have health as a 'constant' and not declared every time is also warmly accepted. Thank you so much!
P.S. Suggestions for shortening the code also accepted but please, I am a beginner. So advanced strategies are beyond my skills right now. I take time to grasp concepts.
You declare the function before the main method, and then you implement the function after the main method.
The problem is, you implement the function as:
int battle(int x)
but this doesn't match your declaration:
int battle();
Just change your function declaration block so the battle function matches the expected signature:
int battle(int x);
void death();
That will get your code compiling, but you are still a number of steps from getting this to work.
I'll give you one starter: instead of passing in the hitpoints into battle, pass the entire player.
void battle(Player &player)
{
// ...
}
Then you can modify the player's hitpoints directly in the battle function.
You would then call this with:
battle(hero);
I am working on a program to code a game called Devil's Dice. I have the logic of code working perfectly, but I am struggling to print the scoreboard to show the games progress. The details of the assignment are below, followed by my code. I don't know where to begin printing the scoreboard as shown in the image I linked.
In our version of Devil's Dice the rules will be as follows:
The player repeatedly rolls a 6-sided die until either a 1 is rolled or the player decides to "hold".
If the player rolls a 1, they lose any points accumulated this turn and the devil gets a turn.
If the player rolls any other number, it is added to their turn total and the player's turn continues.
If a player chooses to "hold", their current turn total is added to their score and the devil gets a turn.
Devil's Logic
If the score is tied or the devil is winning, he will keep rolling until he has at least 21 points (unless he has already reached 100 points)
If the player is winning, the devil will keep rolling until he has at least 30 points (unless he has already reached 100 points)
If the devil rolls a 1, he also loses the points he has accumulated on his turn
If the player chooses to "forfeit", they lose and the game is over.
The player must score 100 points before the devil manages to do so in order to win.
For example, the player, Ann, begins a turn with a roll of 5. Ann could hold and score 5 points, but chooses to roll again. Ann rolls a 2, and could hold with a turn total of 7 points, but chooses to roll again. Ann rolls a 1, and must end her turn without scoring. The devil then rolls the sequence 4-5-3-5-5, chooses to hold, and adds his turn total of 22 points to his score.
There are a few other details about the game logic but i am confident i have it working correctly. I am just wondering how to get a menu with a moving arrow as shown below.
My code looks like this:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() { //just for a school grading program//
#ifdef JARVIS
srand(0);
#else
srand(time(NULL));
#endif
// Call your functions to play your game here...
char userInput;
int diceRoll;
int turnScore = 0;
int totalScore = 0;
int devilScore = 0;
bool isItDevilsTurn = false;
bool winner = false;
int devilWins = 0;
int playerWins = 0;
cout << "---- Welcome to Devil's Dice! ----" << endl;
cout << "Hold[h], roll[r], or forfeit[f]: " << endl;
while (!winner) {
if (!isItDevilsTurn) {
cin >> userInput;
if (userInput == 'h')
{
totalScore = totalScore + turnScore;
cout << "You banked " << turnScore << " points and have a total of " << totalScore << " points" << endl;
isItDevilsTurn = true;
turnScore = 0;
}
if (userInput == 'r')
{
diceRoll = rand() % 6 + 1;
if (diceRoll > 1)
{
cout << "You rolled a " << diceRoll << "!" << endl;
turnScore = turnScore + diceRoll;
}
else
{
cout << "You rolled a 1 :(" << endl;
turnScore = 0;
isItDevilsTurn = true;
}
}
if (totalScore >= 100) {
winner = true;
cout << "You Win!" << endl;
playerWins = playerWins + 1;
}
if (userInput == 'f') {
cout << "Game Over!" << endl;
}
}
else
{
int devilGoal = 21;
if (totalScore > devilScore)
{
devilGoal = 30;
}
while (isItDevilsTurn)
{
diceRoll = rand() % 6 + 1;
if (diceRoll > 1 && turnScore < devilGoal)
{
cout << "devil rolled " << diceRoll << endl;
turnScore = turnScore + diceRoll;
}
else if (diceRoll > 1 && turnScore > devilGoal)
{
devilScore = devilScore + turnScore;
cout << "devil holds " << turnScore << " points and now has " << devilScore << " points" << endl;
isItDevilsTurn = false;
turnScore = 0;
}
else
{
cout << "devil rolled a 1" << endl;
isItDevilsTurn = false;
turnScore = 0;
}
if (devilScore >= 100)
{
cout << "Devil Wins!" << endl;
devilWins = devilWins + 1;
winner = true;
}
}
}
}
cout << "Total Wins: " << playerWins << endl;
cout << "Total Losses: " << devilWins << endl;
fstream output("games.txt");
output << playerWins << " " << devilWins << endl;
return 0;
}
I'm sorry, I'm not too good with tabs, so you just make it looks like you need to. I used a ternary operator to understand if I need to write number or a tab in cuurent line
printf("\tPlayer\t\t\tDevil\n");
printf("\t------\t\t\t-----\n");
for(int i = 10; i >= 0; --i){
printf((totalScore < (i+1)*10 && totalScore >=i*10) ? "%d >" : "\t", totalScore);
printf("--%d", i*10);
printf((turnScore < (i+1)*10 && turnScore >=i*10) ? "< %d" : "\t\t\t", turnScore);
printf((devilTotal < (i+1)*10 && devilTotal >=i*10) ? "%d >" : "\t", devilTotal);
printf("--%d", i*10);
printf((devilTurn < (i+1)*10 && devilTurn >=i*10) ? "< %d" : "\t\t", devilTurn);
printf("\n");
}
How it works? first printf() I evaluate totalScore, if it's less then next value and more than current I print it, otherwise just print tab. Second printf() prints current value. Third printf() evalutes turnScore, if it's less then next value and more than current I print it, otherwise just print 2 tabs.
Same for devil.
It would be the same with cin and cout, it's just that I feel more confident with printf(). If it looks right, all you need to do is work with alignments.