GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: No Line Numbers


fixed program by baldurk
1
 
/*
    Title:         Random guessing game
    Author:        spark, modified by baldurk
    Date:          15-02-04
    Language:      C++
    Description:   an atempt to teach spark good programming practice ;).
                                                                             */

#include <iostream>
#include <cstdlib>
#include <ctime>
 
using namespace std;

const int choice_play = 1;
const int choice_quit = 2;
 
void randomNumberGame();
int difficultyMenu();
int playOrExit();
int randomNumberGenerator();
 
int done = 0;
 
int main() 
{
    bool stillPlaying = true;
    int choice = 0;
 
    choice = playOrExit();

    while(choice == choice_play)
    {
        randomNumberGame();
        choice = playOrExit();
    } // end while
 
    return 0;   
} // end main
 
void randomNumberGame()
{
    int guessesleft = 0, guessTheNumber = 0;
    done = 0; // our flag
 
    guessesleft = difficultyMenu();

    guessTheNumber = randomNumberGenerator();
 
    while(guessesleft && done == 0)
    { 
        int guess;
        cout << "Please input your guess (" << guessesleft << " guesses left): ";
        cin >> guess;
        cout << endl << endl;
 
        if(guess == guessTheNumber)
        {
            cout << "Correct\n";
            done = 1;
        }
        else if(guess < guessTheNumber) 
            cout << "Too low\n";
        else if(guess > guessTheNumber) 
            cout << "Too high\n";

        guessesleft--;
    } // end for

    if(done == 0)
        cout << "You ran out of guesses. The answer was: " << guessTheNumber << endl;
}

int difficultyMenu()
{
    int choice;

    while(true)
    {
        cout << "\nPlease select a difficulty:\n\nEasy: type 1 (you get 10 chances)\n"
            "Medium: type 2 (you get 5 chances)\nHard type 3 (you get 3 chances)\n";
        cin >> choice;

        switch(choice)
        {
            case 1:
                return 10;
                break; // in this case it's useless, but after every case you should put in a break
                // otherwise execution will continue onto the next case.
            case 2:
                return 5;
                break;
            case 3:
                return 3;
                break;
        } // end case
    } // if they haven't picked any of those, you should ask again.

    return 0;
}
 
int playOrExit()
{   
    int choice;
    do
    {
        cout << "Do you wish to play or quit?\n\tPlay: type " << choice_play << "\n\tQuit: type " << choice_quit << "\n";
        cin >> choice;

    } while(choice != choice_play && choice != choice_quit);

    return choice;
}
 
int randomNumberGenerator()
{
    srand(time(NULL));
    return 1 + rand() % 50;
}