I set myself the following additional goal (devised by me):
I wanted to further explore the text input and output of the program. I decided to write a simple text-based game whose point is to repeatedly bash a dragon with a sword. It's possible to drive the flow of the program using commands 'attack', 'flee' and 'showhp'. Inspired by presence of argc and argv[] in main of HelloFor, I searched for their meaning and modified the program to accept integer arguments '-hpd' and '-hpc' to set the initial HP of the dragon and the character and '-cheat' to instantly win the game. My solution was in a file called DragonGame.cc
#include#include #include using namespace std; int main(int argc, char* argv[]) { int hpcharacter, hpdragon, hit; string response = ""; hpcharacter = 40; hpdragon = 60; //Intro talk. cout << "You hear deep breathing. You feel warm." << endl; cout << "You open your eyes to find out that there's an angry" << endl; cout << "dragon staring at you. You draw your sword..." << endl; cout << endl; cout << "You can attack or flee." << endl; cout << "Type 'attack', 'flee' or 'showhp'." << endl; if (argc>1) { //Some arguments were supplied for (int i=1; i< argc; i++) { if (strcmp(argv[i], "-cheat") == 0) { cout << "The dragon had an heart attack. You emerge victorious." << endl; return 0; } else if (i + 1 != argc) { if (strcmp(argv[i], "-hpd") == 0) { hpdragon = atoi(argv[i+1]); } else if (strcmp(argv[i], "-hpc") == 0) { hpcharacter = atoi(argv[i+1]); } else { cout << "Invalid argument(s)." << endl; return 0; } } } } //Game //Play while the dragon or the character aren't dead. while (hpcharacter > 0 && hpdragon > 0) { //while true allows actions which do not take a turn (e.g. showhp) while (1) { //Player response cout << "What do you do?" << endl; getline(cin, response); if (response.compare("showhp") == 0) { cout << "You have " << hpcharacter << " HP." << endl; continue; } else if (response.compare("flee") == 0) { cout << "You're a coward. After you turned your back" << endl; cout << "on the dragon, it fried you." << endl; return 0; } else if (response.compare("attack") == 0) { hit = 2 + (rand() % 3); cout << "You hit the dragon for " << hit << " HP" << endl; hpdragon -= hit; break; } else { //unrecognised command cout << "Please check for errors in yout command." << endl; continue; } } if (hpdragon <= 0) { cout << "You are victorious. The dragon bite the dust." << endl; return 0; } //Dragon attacks cout << "The dragon attacks." << endl; //Dodge? if ((rand() % 8) == 0) { cout << "You dodged the attack." << endl; } else { hit = 1 + (rand() % 6); cout << "The dragon hits you for " << hit << "HP." << endl; hpcharacter -= hit; } if (hpcharacter <= 0) { cout << "You died in an unfair battle." << endl; return 0; } } }