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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
#include <ctime>
#include <cstdlib>
//The following function outputs a basic greeting to the user
void greeting(int pnum) {
if(pnum == 1) {
std::cout << "Please press \"ENTER\" to roll the die.";
} else {
std::cout << "Please press \"ENTER\" again to roll the second die.";
}
std::cin.ignore();
}
//The following function simulates a die roll
int dieroll(void) {
int ran;
srand(time(NULL));
ran = rand()%6+1;
std::cout << "You rolled a " << ran << "." << std::endl;
return ran;
}
//The following adds the 1st and 2nd roll together
int dice(int fdie, int sdie) {
std::cout << "Your total so far is: " << sdie + fdie << std::endl;
return sdie + fdie;
}
// Checks if player won / lost / can keep rolling.
int results(int total) {
if (total == 7 || total == 11) {
std::cout << "You won! Congratulations!";
return 0;
} else if (total == 2 || total == 3 || total == 12) {
std::cout << "You lose. Try again.";
return 0;
} else {
std::cout << "You may continue to roll." << std::endl << std::endl;
return 1;
}
}
// Main Funtion
int main(void) {
int counter, total, seconddie, firstdie;
char secondstart;
do {
greeting(1);
firstdie = dieroll();
greeting(2);
seconddie = dieroll();
total = dice(firstdie, seconddie);
} while(results(total)!=0);
std::cin.ignore();
return 0;
}
|
What I had to change / is not good:
1. It's not good to use
using namespace std;
.
2. It's not good to use
system();
.
3. To check is something is equal to something else, use
==
.
4. You had some errors with your if statement which I fixed.
5. You have to use
||
(or) instead of
&&
(and) in this case.
6. Just use
std::cin.ignore();
instead of creating a character and etc... (Save time and memory.)
7. You need a
while
loop to keep the game running if the person is still rolling.
8. Got rid of
#include <iomanip>
because there is no use for it.
9. You only need one dice roll function. Also you were printing another number on the screen than the one your were returning.
10. Saved some memory on your greeting functions.
11. Fixed tabs / spaces in your program.
What you did right:
1. Good comments. Keep it up!
In the end:
1. Made your program more user friendly.
2. Turned 135 lines of broken code into 59 lines of quality code.
3. Saved memory.
4. Saved time (program isn't slower than it was).