I am a complete noob at programming and I am having multiples errors that says "expected a declaration"
A project was assigned to us that required to create a text base game with characters attacking opponents.
We are to make characters and when we tell them to attack we must enter the correct key to attack.
This is what I have so far:
#include <cstdlib>
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
int Opponent;
int showOpponentHealth(int OpponentHealth, int Attack);
int showHealth(int Health, int OpponentAttack);
int showMagic(int Magic);
{ //Error: expected a declaration
public:
Opponent() : OpponentAttack(0), OpponentHealth(3);
{
OpponentAttack = rand() % 100;
OpponentHealth = rand() % 6 + 10;
}
}
int getAttack(Opponent);
{ //Error: expected a declaration
AttRoll = Rand() % 100
if (AttRoll < getAtt)
hit
{
AttType = 1 - 3
if (AttType == 1)
return 30
else if (AttType == 2)
return 50
else if (AttType == 3)
return 70
}
float character::getHeal()
{
magicCost = magic - 6;
Heal = rand() % 3 + 5;
cout << "Heal value= " << heal << ".\n";
return Heal;
}
}
void Battle()
{
int Health = rand() % 6 + 10;
int OpponentHealth = rand() % 6 + 10;
int hit;
}
long timeTest()
{
//seed the random number generator
srand(GetTickCount64());
//rand will give a number between 0 and max integer value
int waitTime = rand() % 5 + 1;
for (int i = waitTime; i>0; i--)
{
cout << "*";
Sleep(1000); //wait for 1 second
}
char typeThis = rand() % 26 + 97;
cout << typeThis << ":";
char playerResponse;
//this is the window function I'm using to get the time: ULONGLONG WINAPI GetTickCount64(void);
ULONGLONG startTime = GetTickCount64();
cin >> playerResponse;
ULONGLONG endTime = GetTickCount64();
if (playerResponse != typeThis)
return -1;
long deltaTime = endTime - startTime;
return deltaTime;
}
do //syntax error
{ //Error: expected a declaration
cout << " Attack Opponent? \n Yes = 1\n"
cin >> Attack Opponent;
if (AttackOpponent == 1)
{
OpponentHealth = showOpponentHealth(OpponentHealth, Attack);
Health = showHealth(health, OpponentAttack);
cout << "You attacked the Opponent with a light attack.";
cout << "The Opponent now has " << OpponentHealth << "health left.";
if (OpponentHealth <= 0)
{
cout << "You Win!";
}
else if (OpponentHealth > 0)
{
cout << "Opponent attacks back";
cout << "You have" << Health << "health left,";
}
else if (AttackOpponent == 2)
cout << "You attacked the Opponent with a medium attack.";
cout << "The Opponent now has " << OpponentHealth << "health left.";
{ //Error: expected a declaration
else if (AttackOpponent == 3)
cout << "You attadcked the Opponent with a heavy attack.";
cout << "The Opponent now has " << Opponent Health << "health left.";
}
} //Error: expected a declaration
int showOpponentHealth(int OpponentHealth, int Attack)
{
OpponentHealth = OpponentHealth - Attack;
return OpponentHealth;
}
int showHealth(int Health, int OpponentAttack)
{
Health = Health - OpponentAttack;
return Health;
}
}
int main()
{
cout << "Try the timeTest: " << timeTest() << endl;
int Health = rand() % 6 + 10;
if (Health <= 0)
cout << "You Died. Game Over." << endl;
int Magic = 10
else (Magic <= 0)
cout << "No more Magic." << endl;
system("Pause");
return0;
}
the errors pop up at the brackets and at "do"
Your do{ ... } loop is outside of any function. It must be inside of a function - the compiler is telling you it expects a declaration of a function like:
long timeTest()
Did you mean for the do-loop to be inside timeTest()?
Related
I've been making my C++ text game. Gone fairly well so far. I had a few delays with some mistakes I have made. Got most of that fixed up. Now I am working on the level up and experience points system. And IDK how to keep that number updated so it's knowns that it reaches level 55. Here's the code:
(first program ever)
//#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string.h>
using namespace std;
bool gameRunning = true;
char Yarra = 'P';
char Dragon = 'D';
char map[28];
class Player;
class Enemy {
private:
int lvl;
public:
int health;
Enemy() {
int randomNumber = rand();
int enemy_life = (randomNumber % 7) + 2;
health = enemy_life;
lvl = 1;
}
void attack(Player& p);
friend class Player;
};
class Final_dragon {
public:
int lvl;
int health;
Final_dragon() {
health = 10;
lvl = 2;
}
void attack(Player& p);
friend class Player;
};
class Player {
private:
public:
int health;
int exp;
int lvl;
Player(bool hero) {
if(hero) {
health = 100;
lvl = 1;
exp = 0;
} else {
health = 1;
}
}
void attack(Enemy& e);
void lvlUp(Player& p);
friend class Enemy;
friend class Final_boss;
};
void Player::attack(Enemy& e) {
int randomNumber = rand();
int dmg = (randomNumber % 2) + 0;
cout << "\nYou've done " << dmg << " damage!" << endl;
e.health -= dmg;
}
void Enemy::attack(Player& p) {
// int randomNumber = rand();
// int dmg = (randomNumber % 20) + 0;
int dmg = 2;
cout << "\nThe Enemy does " << dmg << " damage to you!\n" << endl;
p.health -= dmg;
}
void Player::lvlUp(Player& p) {}
int main() {
int display;
char playerInput{};
char move;
char action;
map[0] = Yarra;
map[27] = Dragon;
cout << "Map: " << map[0];
for(display = 1; display < 27; display++) {
map[display] = '*';
cout << map[display];
}
cout << map[27];
cout << endl
<< endl
<< "Press '1' Travel to another space on the board \n"
<< "Press '2' Dismount and explore the current space " << endl;
display = 0; // Start at map[0]
while(gameRunning == true) {
Player p(true);
do {
cin >> move; // Get user input
if(move == '1') // If input is '1'
{
srand(time(0));
int dice = (int)(1 + rand() % 6);
cout << "You moved: " << dice << " steps" << endl;
map[display] = '*'; // Remove old location of player
display = display + dice; // Increase display location
map[display] = 'P'; // Insert player in new map array location
cout << "Your current location: " << display
<< endl; // Player current location
}
if(move == '2') // If input is '2'
{
cout << "Your current location: " << display
<< endl; // Player current location
srand(time(0));
int monster_dice = (int)(1 + rand() % 14); // Random monster
cout << "Monster location: " << monster_dice << endl
<< endl; // monster location
if(display == monster_dice) {
cout << "You've encountered a Enemy! Press \"a\" to attack"
<< endl
<< endl;
Enemy e;
cout << "HP of the monster you encounter: " << e.health << endl;
cin >> action;
if(action == 'a' || action == 'A') {
do {
p.attack(e);
cin.ignore(1);
if(p.health <= 0) {
system("CLS");
cout << "\t\n\nYou have died..." << endl;
cout << "\t\nGAME OVER!" << endl << endl;
return 0;
}
if(e.health >= 1) {
e.attack(p);
cin.ignore(1);
}
} while(e.health >= 0);
if(e.health <= 0) {
cout << "\n\nYou defeat the Enemy! *Vistory Music*\n"
<< endl;
cout << "You gained " << 100
<< " experience from the Boar." << endl;
p.exp += 100;
}
if(p.exp >= 200 && p.exp <= 300) {
cout << "\nYou've gone up to level 2!" << endl;
p.lvl++;
p.health += 50;
}
if(p.exp >= 300 && p.exp <= 400) {
cout << "\nYou've gone up to level 3!" << endl;
p.lvl++;
p.health += 40;
}
if(p.exp >= 400 && p.exp <= 500) {
cout << "\nYou've gone up to level 4!" << endl;
p.lvl++;
p.health += 50;
}
if(p.exp >= 600 && p.exp <= 700) {
cout << "\nYou've gone up to level 5!" << endl;
p.lvl++;
p.health += 50;
}
}
}
}
} while(move != '1');
for(int x = 0; x <= 28; x++) {
cout << map[x];
}
if(display == 27 || display > 27) // If player at end of map array, end game
{
Final_dragon d;
if(p.lvl == 2) {
cout << "Ready for the fight" << endl;
} else {
system("CLS");
cout << "\nAlas, the dragons eyes stare at you and places you "
"under his spell. You try to move but fail to do so and "
"find yourself torched by the dragons fire.If only you had "
"more experience, you could have seen it coming."
<< endl;
cout << "\t\nGAME OVER!" << endl
<< endl; // Show text explaining why game ended
}
}
}
}
while(gameRunning == true) {
Player p(true);
You create a new hero player in each iteration. All experience and levels gained will be reset back to a newly created Player.
Create the Player before the loop:
Player p(true);
while(gameRunning == true) {
If you want the player to be able to fight the dragon if he/she is at least at the same level as the dragon, change the condition from if(p.lvl == 2) to if(p.lvl >= d.lvl).
You should seed the pseudo random number generator, i.e., call srand(), only once during the programs execution. Call it once when the program starts and never again.
If you are using C++11 or newer, you should use the <random> library instead of srand() and rand(). The same rule applies for those modern generators. Only seed them once.
A function to create a random number could look like this:
#include <random>
// A function to return a random number generator.
inline std::mt19937& generator() {
// the generator will only be seeded once since it's static
static std::mt19937 gen(std::random_device{}());
return gen;
}
// A function to generate int:s in the range [min, max]
int my_rand(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(generator());
}
I'm creating a program where a user tries to guess the amount of times two dice have to roll to reach the totalsum of 100.
I've finished the loop but now I'm stuck on the point where I want the program to compare the two variables. I've googled but nothing has been coming up regarding the issue.
In regards to the code, here's what I have:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int min_value=1;
const int max_value=6;
int die1,die2,sum,totalRolls, totalSum, prediction;
unsigned seed = time(0);
srand(seed);
sum=0;
totalRolls=0;
totalSum=0;
cout << "How many rolls will it take to reach a total of 100?\n";
cin >> prediction;
while (totalSum <= 100)
{
cout << "Rolling the die\n";
die1=(rand() % (max_value - min_value + 1) + min_value);
die2=(rand() % (max_value - min_value + 1) + min_value);
cout << die1 << endl;
cout << die2 << endl;
sum=die1+die2;
totalSum+=sum;
cout << "Your current total is " << totalSum << endl;
totalRolls++;
cout << "Last roll number = " << totalRolls << endl;
}
if (totalRolls <= 5)
{
cout << "Amazing!\n";
}
else if (totalRolls <=10)
{
cout << "Good\n";
}
else if (totalRolls <= 15)
{
cout << "Okay\n";
}
else if (totalRolls <= 20)
{
cout << "Try harder\n";
}
system("Pause");
return 0;
}
I honestly just don't know how to compare the predicted total number of rolls compared to the actual rolls it took.
This question already has answers here:
Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]
(4 answers)
Closed 5 years ago.
I decided to try to make a little game. It's a simple survival game. Part of it has people try to survive as long as they can by choosing options. I've scaled down the game as much as possible from 1000 lines to this for the minimum case.
At one part of the game it asks, "You were visited by a gifting clown. On a scale of 0-10, how badly do you want a gift?"
If they answer 0-10, the loop works fine. If they answer with a character, like y or n, the loop basically forces the game to execute where it no longer asks players for input on any other choices.
A previous while loop works, one where it will continue so long as the player is alive. This clown while loop is nested inside of it. I have broken up the while loop with the clown section to where I think the problem is... And also included the full code just in case it's not inside there.
My goal is simply if a character is put into it, that it doesn't break this game.
main.cpp - clown section
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
main.cpp - Condensed code
#include <iostream>
#include <iomanip>
#include <random>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand (time(NULL));
int randNumber = 0;
int food = 4;
int wood = 4;
int medicine = 2;
int bullets = 8;
int money = 25;
int randomEncounter = 0;
int hunt = 0;
bool axe = false;
int axeTemp = 0;
int axeBonus = 0;
int lumberTemp = 0;
int lumber = 0;
int findStore = 0;
int storeChoice = 0;
bool gun = false;
int gunSearch;
int gunTemp;
int gunBonus = 0;
int gunFind = 0;
// int searches;
// int searchesBonus;
int farmFind = 0;
int farmFood = 0;
int farmSearch = 0;
bool farm = false;
string description;
int foodTemp = 0;
int woodTemp = 0;
int medicineTemp = 0;
int bulletsTemp = 0;
int moneyTemp = 0;
int huntTemp = 0;
int huntSuccess = 0;
char huntChoice;
int encounterFood = 0;
int encounterWood = 0;
int encounterBullets = 0;
int encounterMedicine = 0;
int encounterHurt = 0;
unsigned int encounterChoice = 0;
int hurt = 0;
int health = 3;
int healthMax = 3;
int days = 1;
char action = '0';
char pause = '1';
char classChoice;
char mainChoice;
bool clown = true;
int clownHealth = 5;
char clownChoice;
int yourShot = 0;
int clownShot = 0;
string place;
//Food 1 per day per person. Can expand to include more people.
//Fuel 1 per day, takes that much to stay warm even if fewer people
//Medicine used one per wound
//Bullets 1 to hunt, though can spend more to increase chance of success.
//Days how many days that they have survied.
//Health, everyone starts with three health. Good, okay, bad, dead.
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets << " Health: " << health << endl;
while (health > 0){
cout << "\nDay: " << days;
cout << "\nFood: " << food
<< "\nWood: " << wood
<< "\nMedicine: " << medicine
<< "\nBullets: " << bullets
<< "\nHealth: " << health
<< "\nMoney: " << money << endl;
if (food >= 1){
food--;
}
if (wood >= 1){
wood--;
}
if (food <= 0){
health--;
cout << "Health lost due to lack of food" << endl;
}
if (health < healthMax && medicine > 0){
health++;
medicine--;
cout << "Health pack used to heal your character\nHealth : " << health << endl;
}
action = '0';
cout << "\n1: Find food" << endl;
cout << "What's your action? ";
cin >> action;
cout << endl;
if (action == '1'){
//
//Section for random sites to search.
//
//
randNumber = rand() % 4;
description = "";
//Maybe + days at the end, and subtract some, so that they eventually run out of places to check.
if (randNumber >= 0 && randNumber < 2) {
place = "supermarket";
foodTemp = (rand() % 4) + 1;
woodTemp = (rand() % 2) + 0;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 1;
moneyTemp = (rand() % 5) + 5;
}
if (randNumber >= 2 && randNumber < 4) {
place = "boat house";
foodTemp = (rand() % 2) + 1;
woodTemp = (rand() % 4) + 1;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 0;
moneyTemp = (rand() % 3) + 0;
}
cout << "You have come to the " << place << "." << endl;
cout << description << endl;
food += foodTemp;
wood += woodTemp;
bullets += bulletsTemp;
medicine += medicineTemp;
money += moneyTemp;
if (foodTemp > 0)
cout << "You have found " << foodTemp << " food." << endl;
if (woodTemp > 0)
cout << "You have found " << woodTemp << " wood." << endl;
if (medicineTemp > 0)
cout << "You have found " << medicineTemp << " medicine." << endl;
if (bulletsTemp > 0)
cout << "You have found " << bulletsTemp << " bullets." << endl;
if (moneyTemp > 0)
cout << "You have found " << moneyTemp << " money." << endl;
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets
<< " Health: " << health << " Money: " << money << endl;
//End of search rooms.
}
//Random encounter chance to see if they can gain additional items.
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
//Option to attack clown
//
//
}
//End of random encounter from the clown.
//Pause mechanic to prevent the game from cycling.
// pause = 'b';
// while (pause != 'a'){
// cout << "\nEnter a to continue: ";
// cin >> pause;
// }
//End of game message
cout << endl;
if (days == 100){
cout << "You have made it to 100 days. You have beaten this game. You can quit now, or try to see how long you'll last." << endl;
}
//Add day at end of while loop.
days++;
}
cout << "You have died after " << days << " days" << endl;
}
From another Stack Overflow question...
When an error occurs when reading from a stream, an error flag gets
set and no more reading is possible until you clear the error flags.
That's why you get an infinite loop.
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I was just wondering why playerHp doesn't stay at it's value but resets to 30 each time I call the function. Is it because the variable is local, and if so how do I make it go global from within the function?
I'm new to programming so easy explanations would be nice.
I'm also aware this is "spaghetti code", but if you have the time and energy, cleaning it up would be much appreciated.
#include <iostream>
#include <string>
#include <cstdlib>
//RETURN CODES 1=WON 2=RAN AWAY 3=SLAIN 4=globalWin 5=GlobalLose
using namespace std;
int playerHp;
int enemyHp;
string enemyName;
int dmg()
{
int modifier = rand() % 10 ; // 0-9
return 15 + modifier;
}
int playerDmg()
{
int modifier1 = rand() % 10 ; // 0-9
return 15 + modifier1;
}
int enemyDmg()
{
int modifier2 = rand() % 10 ; // 0-9
return 10 + modifier2;
}
int fight(int playerHp, int enemyHp, string enemyName)
{
int constwhile = 1;
string input;
cout << "You encountered a ";
cout << enemyName <<"\n";
while (constwhile = 1) {
cout << "What will you do?\n";
cout << "Options Fight or Flee: " << flush;
cin >> input;
cin.ignore();
cin.get();
if (input == "Fight" || input == "fight") {
int damageDone = playerDmg();
int finalEnemyHp = enemyHp - damageDone;
cout << "You did ";
cout << damageDone;
cout << " damage" << "\n";
enemyHp = finalEnemyHp;
if (enemyHp < 0) {
cout << "Congratulations! You won!"<<"\n";
return 1;
}
cout << "The monster now has ";
cout << enemyHp;
cout << " health"<<"\n";
} else if (input == "Flee" || input == "flee") {
cout << "You ran away...";
return 2;
} else {
cout<<"Invalid Input"<<"\n";
}
cout << "The enemy fights back!"<< "\n";
int damageDone = enemyDmg();
int finalPlayerHp = playerHp - damageDone;
cout << "It did ";
cout << damageDone;
cout << " damage" << "\n";
playerHp = finalPlayerHp;
if (playerHp < 0) {
cout << "You have been slain...";
return 3;
}
cout << "You now have ";
cout << playerHp;
cout << " health"<<"\n";
}
}
int main()
{
int playerHp = 30;
while(playerHp > 1) {
int fightOutcome = fight(playerHp, rand() % 30, "monster");
if (fightOutcome == 3) {
return 5;
} else if (fightOutcome == 2) {
return 5;
}
}
return 4;
}
The problem are that your global variable are shadow by local defined on function
int fight(int playerHp, int enemyHp, string enemyName)
A fast way to fix your problem is to pass the variables as reference if you want yo keep the value assigned inside function fight
int fight(int &playerHp, int &enemyHp, string &enemyName)
If you want to use a global variable, there must be no local variable or parameter with the same name.
The following will always change the local variable:
int myVar = 0;
void foo(int myVar)
{
myVar = 100;
}
int main()
{
foo(myVar);
cout << myVar;//0
return 0;
}
Now you could either accept a pointer instead of a value, or you could remove the parameter entirely. But I don't really like global pollution, so I would prefer the pointer:
with pointer:
int myVar = 0;
void foo(int* myVar)
{
*myVar = 100;
}
int main()
{
foo(&myVar);
cout << myVar;//100
return 0;
}
without pointer:
int myVar = 0;
void foo()
{
myVar = 100;
}
int main()
{
foo(myVar);
cout << myVar;//100
return 0;
}
I have a dice game
int userGame()
{
cout << " User turn --- Press 2 to roll" << endl;
cin >> userInput;
if ( userInput == 2 )
{
Dice ();
cout << "The user rolled Dice 1 =" << die1 << " and Dice 2 = " << die2 << endl;
cout << "Total = " << die1 + die2 << endl;
}
else {
cout << "Wrong input. Try again";
//userGame();
}
return (die1 + die2);
}
and now in int main , I have -
int main ()
{
// set the seed
srand(time(0));
userGame();
while (true)
{
if (userGame() == 7 || userGame() == 11)
{
cout << "You won" << endl;
break;
}
else if (userGame() == 2)
{
cout << "You loose" <<endl;
break;
}
else
{
break;
}
}
return 0;
Dice ();
#include<iostream>
#include<ctime> // for the time() function
#include<cstdlib> // for the srand() and rand() functions
using namespace std;
int compInput;
int userInput;
int die1 = 0;
int die2 = 0;
int Dice ()
{
// roll the first die
die1 = (rand() % 6 ) + 1;
// roll the second die
die2 = (rand() % 6 ) + 1;
}
But the output for some reason is not showing up right. Once it will show that the user won when the output is 7 and other time, it would just continue with the game.
What am i doing with the loop in main()?
Thanks
if (userGame() == 7 || userGame() == 11)
This line is your problem. C++ uses short circuit evaluation. In this case, if userGame() == 7 succeeds, it doesn't check the second half. However, if it fails userGame() will be called again for the second half, meaning you'll play twice before going into the code section for the if.
while (true)
{
int result = userGame();
if (result == 7 || result == 11)
{
cout << "You won" << endl;
break;
}
else if (result == 2)
{
cout << "You loose" <<endl;
break;
}
else
{
break;
}
}