So, just for fun I have been making a small text-based game to test my knowledge of C++ so far. However, I have encountered an odd error where commands will execute once, and then after that return the same output repeatedly. Could anyone analyze this and see what's wrong? Here is the source (sorry, it is a bit long)
/*
* File: main.cpp
* Author: dim
* A small text based game
*
* Created on March 10, 2012, 6:22 PM
*/
#include <iostream>
#include <cstdlib>
using namespace std;
struct Item {
double health;
double strength;
double weight;
unsigned int position;
Item(double hp, double strong, double weight, unsigned int position)
{
this->health=hp;
this->strength=strong;
this->weight=weight;
this->position=position;
}
};
double calcDamage(Item item) {
const int modifier=4;
double damage;
damage+=item.strength*modifier;
if(item.weight<=300)
damage+=item.weight;
else
damage+=item.weight*modifier;
return damage;
}
void list()
{
cout << "\nls: List commands";
cout << "\na: Attack a nearby opponent.";
cout << "\nmr: Move your character right.";
cout << "\nml: Move your character to the left."<<endl;
}
int attack(Item player, Item toAttack) //a
{
double damage=0;
if(player.position-toAttack.position>1)
goto done;
damage=calcDamage(player);
toAttack.health-=damage;
cout << "\nDid " <<damage<<" damage." <<endl;
if(player.position-toAttack.position>1)
goto done;
damage=calcDamage(toAttack);
player.health-=damage;
cout <<"You took "<<damage<<" damage." <<endl;
done:
cout << "Your health is: " <<player.health <<endl;
cout << "Your opponent's is "<<toAttack.health<<endl;
if(player.health<=0) {
cout<<"You are dead." <<endl;
return 1;
}
else if(toAttack.health<=0) {
cout <<"You have killed your opponent." <<endl;
return 1;
} else
return 0;
}
void moveRight(Item toMove)
{
if(toMove.position+1<=10)
toMove.position++;
cout <<"Your position is: "<<toMove.position <<endl;
}
void moveLeft(Item toMove)
{
if(toMove.position-1>0)
toMove.position--;
cout <<"Your position is: "<<toMove.position <<endl;
}
int main() {
cout <<"Mayhem - Version 1" <<endl;
Item player(1000.,5.,150.,1);
Item opponent(1000.,5.,150.,1);
cout <<"To quit the game type gq" <<endl
<<"For a list of command, type ls"<<endl;
string command=""; //Still good to assign.
int stopper=0;
do {
//Command input
cout <<">";
cin>>command;
cout <<endl;
if(command=="ls")
list();
if(command=="a")
stopper=attack(player, opponent);
if(command=="mr")
moveRight(player);
if(command=="ml")
moveLeft(player);
}while(command!="gq"||stopper);
return 0;
}
Here is some sample output:
Mayhem - Version 1
To quit the game type gq
For a list of command, type ls
>ml
Your position is: 1
>ml
Your position is: 1
>mr
Your position is: 2
>mr
Your position is: 2
>a
Did 170 damage.
You took 170 damage.
Your health is: 830
Your opponent's is 830
>a
Did 170 damage.
You took 170 damage.
Your health is: 830
Your opponent's is 830
>gq
Also, this is my first time making a thread on Daniweb, so feel free to alert me if I did something wrong.