Extreme programming

Nothing is impossilbe! Extreme Optimizing

Friday, February 18, 2005

C++ Programming in Game Development

Recently, I am reading "Beginning C++ Game Programming " ( by Michael Dawson ), which is an interesting book. It is suitable not only to C++ novices but experieced programmers. The most important point is that we can learn something in a exicting practical world: game programming.

1 Comments:

  • At February 18, 2005 at 8:41:00 PM PST, Blogger Shunkai Fu said…

    // Hangman
    // The classic game of hangman

    #include "iostream"
    #include "string"
    #include "vector"
    #include "algorithm"
    #include "ctime"
    #include "cctype"

    using namespace std;

    int main()
    {
    //setup
    const int MAX_WRONG = 8; //maximum number of incorrect guesses allowed

    vector[string] words; //collection of possible words to guess
    words.push_back("GUESS");
    words.push_back("HANGMAN");
    words.push_back("DIFFICULT");
    words.push_back("TOEFL");
    words.push_back("MONTREAL");
    words.push_back("SHANGHAI");
    words.push_back("WASHINGTON");
    words.push_back("MICROSOFT");

    srand(time(0));
    random_shuffle(words.begin(), words.end());
    const string THE_WORD = words[0];
    //word to guess
    int wrong = 0;
    //number of incorrect guesses
    string soFar(THE_WORD.size(), '-'); //word guessed so far
    string used = "";
    //letters already guessed//main loop
    while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
    {
    cout << "\n\nYou have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
    cout << "\nYou've used the following letters:\n" << used << endl;
    cout << "\nSo far, the word is:\n" << soFar << endl;

    cout << "Welcome to Hangman. Good luck!\n";
    char guess;
    cout << "\n\nEnter your guess: ";
    cin >> guess;
    guess= toupper(guess); //make uppercase since secret word in uppercase
    while (used.find(guess) != string::npos) //if the inputted char is not in GUESS list
    {
    cout << "\nYou've already guessed " << guess << endl;
    cout << "Enter your guess: ";
    cin >> guess;
    guess = toupper(guess);
    }

    used += guess; //append a newly input guessing char at the tail

    if (THE_WORD.find(guess) != string::npos)
    {
    cout << "That's right! " << guess << " is in the word.\n";

    //update soFar to include newly guessed letter
    for (int i = 0; i < THE_WORD.length(); ++i) //display explicitly in the HIDEEN WORD the guessed char
    if (THE_WORD[i] == guess)
    soFar[i] = guess;
    }
    else
    {
    cout << "Sorry, " << guess << " isn't in the word.\n";
    ++wrong;
    }
    }
    //shut down
    if (wrong == MAX_WRONG)
    cout << "\nYou've been hanged!";
    else
    cout << "\nYou guessed it!";

    cout << "\nThe word was " << THE_WORD << endl;
    cout << "\nPress any key to exit!" << endl;

    char c;
    cin >> c;
    return 0;
    }

     

Post a Comment

<< Home