Game Programming

Ubuntu Korea Community Wiki
imported>Drake님의 2014년 7월 10일 (목) 13:04 판 (새 문서: == 게임 만들기 == * C++로 게임 제작의 기본기를 쌓는것이 목적 === 왜 C++인가 === * C++은 빠른편이고, 고급언어인 편에 속한다. * 사실상 업계 ...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)
둘러보기로 이동 검색으로 이동

게임 만들기

  • C++로 게임 제작의 기본기를 쌓는것이 목적

왜 C++인가

  • C++은 빠른편이고, 고급언어인 편에 속한다.
  • 사실상 업계 표준임.
  • C에 비해 Object Oriented 프로그래밍이 쉽다.

Game Over

  • C++로 Game Over를 짜보자Hello world랑 뭐가 다른건데!!

<source lang="c"> // Game Over // A first C++ program

  1. include <iostream>

int main() {

   std::cout << "Game Over!" << std::endl;
   return 0;

} </source>

  • Game Over 2.0을 짜보자조또 바뀐것 없다.
  • 네임스페이스를 써서

<source lang="c"> // Game Over 2.0 // Demonstrates a using directive

  1. include <iostream>

using namespace std;

int main() {

   cout << "Game Over!" << endl;
   return 0;

} </source>

  • Game Over 3.0이다.반복학습 쩐다

<source lang="c"> // Game Over 3.0 // Demonstrates using declarations

  1. include <iostream>

using std::cout; using std::endl;

int main() {

   cout << "Game Over!" << endl;
   return 0;

} </source>

비싼 계산기

  • 연산자를 이해하기 위해 비싼 계산기를 짜보자.

<source lang="c"> // Expensive Calculator // Demonstrates built-in arithmetic operators

  1. include <iostream>

using namespace std;

int main() {

   cout << "7 + 3 = " << 7 + 3 << endl;
   cout << "7 - 3 = " << 7 - 3 << endl;
   cout << "7 * 3 = " << 7 * 3 << endl;
   cout << "7 / 3 = " << 7 / 3 << endl;
   cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;
   cout << "7 % 3 = " << 7 % 3 << endl;
   cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;
   cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;
   return 0;

} </source>

게임 스탯

  • 비행 슈팅게임에서 상태출력에 대해 생각하려 한다.

<source lang="c"> // Game Stats // Demonstrates declaring and initializing variables

  1. include <iostream>

using namespace std;

int main() {

   int score;
   double distance;
   char playAgain;
   bool shieldsUp;
   short lives, aliensKilled;
   score = 0;
   distance = 1200.76;
   playAgain = 'y';
   shieldsUp = true;
   lives = 3;
   aliensKilled = 10;
   double engineTemp = 6572.89;
   cout << "\nscore: " << score << endl;
   cout << "distance: " << distance << endl;
   cout << "playAgain: " << playAgin << endl;
   // Bool 표현은 애매하므로 shieldup은 생략한다.
   cout << "lives: " << lives << endl;
   cout << "aliensKilled: " << aliensKilled << endl;
   cout << "engineTemp: " << engineTemp << endl;
   int fuel;
   cout << "\nHow much fuel? ":
   cin >> fuel;
   cout << "fuel: " << fuel << endl;
   typedef unsigned short int ushort;
   ushort bonus = 10;
   cout << "\nbonus: " << bonus << endl;
   return 0;

} </source>

  • 어디서 많이 보던 것들이지?겜 좀 해봐야 겜을 만들징
  • 이제 좀 계산하는 방법에 대해 알아보자.

<source lang="c"> /* game_stats2.cc */ // Game Stats 2.0 // Demonstrates arithmetic operations with variables

  1. include <iostream>

using namespace std;

int main() {

   unsigned int score = 5000;
   cout << "score: " << score << endl;
   // 값을 살짝 바꾼다.
   score = score + 100;
   cout << "score: " << score << endl;
   // 값 증가의 다른 버전
   score += 100;
   cout << "score: " << score << endl;
   // 값 증가의 또다른 버전
   int lives = 3;
   ++ lives;
   cout << "lives: " << lives << endl;
   lives = 3;
   lives++;
   cout << "lives: " << lives << endl;
   lives = 3;
   int bonus = ++lives * 10;
   cout << "lives, bonus = " << lives << ", " << bonus << endl;
   lives = 3;
   bonus = lives++ * 10;
   cout << "lives, bonus = " << lives << ", " << bonus << endl;
   // 정수 최대값은 결국?
   score = 4294967295;
   cout << "\nscore: " << score << endl;
   ++score;
   cout << "score: " << score << endl;
   return 0;

} </source>

  • 자. 이제 3.0이다뭔 이따위것까지 3.0이여

<source lang="c"> /* game_stats3.cc */ // Game Stats 3.0 // Demonstrates constants

  1. include <iostream>

using namespace std;

int main() {

   const int ALIEN_POINTS = 150;
   int aliensKilled = 10;
   int score = aliensKilled * ALIEN_POINTS;
   cout << "score: " << score << endl;
   enum difficulty (NOVICE, EASY, NORMAL, HARD, UNBEATABLE);
   difficulty myDifficulty = EASY;
   enum ship (FIGHTER = 25, BOMBER, CRUISER = 50, DESTROYER = 100);
   ship myShip = BOMBER;
   cout << "\nTo upgrade my ship to Cruiser will cost " << (CRUISER - myShip) << " Resource Points.\n";
   return 0;

} </source>

  • 상수의 사용법이다.
  • 안바뀌는건 const 지정을 해놓으면 나중에 편하다.
  • 열거형 변수. 짜증나게 값 입력을 안해놨으니 이해가 힘들거임.좀 복붙이라도 하던지.
  • 한번 돌려보면 어느정도 감이 잡히는거고, 내용을 설명하기엔 좀..이럴때 책이 필요한거임. 다른 언어 해본사람은 금방 눈에 들어올거고.

Lost Fortune

  • 기본을 어느정도 했으면 진짜 간단한거 하나 해보자.

<source lang="c"> /* lost_fortune.cc */ // Lost Fortune // A personalized adventure

  1. include <iostream>
  2. include <string>

using std::cout; using std::cin; using std::endl; using std::string;

/* string을 포함했다. 이건 표준 라이브러리의 일종인데, 문자열 처리를 위한 라이브러리다. */

/* 사용자 정보를 입력받자. */ int main() {

   const int GOLD_PIECES = 900;
   int adventurers, killed, survivors;
   string leader;
   // 플레이어 정보를 입력받는다.
   cout << "Welcome to Lost Fortune\n\n";
   cout << "Please enter the following for your personalized adventure\n";
   cout << "Enter a number: ";
   cin >> adventurers;
   cout << "Enter a number, samller than the first: ";
   cin >> killed;
   survivors = adventurers - killed;
   cout << "Enter your last name: ";
   cin >> leader;
   /* GOLD_PIECES는 모험가들이 찾는 행운의 금 조각이다. adventurers는 모험가의 숫자, killed는 모험하다 뒈진 사람의 숫자다. 여기서는 당신이 생존자 리더다. */
   // 스토리텔링
   cout << "\n A brave group of " << adventurers << " set out on a quest ";
   cout << "-- in search of the lost treasure of the Ancient Dwarves. ";
   cout << "The group was led by that legendary rogue. " << leader << ".\n";
   cout << "\n Along the way. a band of marauding ogres ambushed the aprty. ";
   cout << "All fought bravely under the command of " << leader;
   cout << ", and the ogres were defeated, but at a cost. ";
   cout << "Of the adventurers. " << killed << " were vanquished. ";
   cout << "leaving just " << survivors << " in the group.\n";
   cout << "\nThe party was about to give up all hope. ";
   cout << "But while laying the deceased to rest. ";
   cout << "they stumbled upon the buried fortune. ";
   cout << "So the adventurers split " << GOLD_PIECES << " gold pieces.";
   cout << leader << " held on to the extra " <<  (GOLD_PIECES % survivors);
   cout << " pieces to keep things fair of course.\n";
   return 0;

} </source>

  • 별 게임도 아닌것 같은데.. 스토리텔링하고 끝나네..뭐 첨엔 다 그런거야

Score Rater

  • 점수 매기기, 조건문에 대한 이해를 해보자.

<source lang="c"> /* score_rater.cc */ // Score Rater // Demonstrates the if statement

  1. include <iostream>

using namespace std;

int main() {

   if(true)
       cout << "This is always displayed.\n\n";
   if(false)
       cout << "This is never displayed.\n\n";
   int score = 1000;
   if(score)
       cout << "Okay, at least you didn't score zero.\n\n";
   if(score > 500)
       cout << "You scored over 500. Nice.\n\n";
   if(score == 1000)
   {
       cout << "You scored a perfect 1000!\n";
       cout << "Now that's impressive.\n";
   }
   if(score > 500)
   {
       cout << "You scored at least 500.\n";
       if(score >= 1000)
           cout << "You scored 1000 or more!\n";
   }
   return 0;

} </source>

  • 점수매기기 2.0. 이번엔 입력을 받아보자구.

<source lang="c"> /* score_rater2.cc */ // Score Rater 2.0 // Demonstrates the else caluse

  1. include <iostream>

using namespace std;

int main() {

   int score;
   cout << "Enter your score: ";
   cin >> score;
   if(score > 500)
       cout << "\nYou got over 500. Nice score.\n";
   else
       cout << "\nYou got 500 or less. Nothing to brag about.\n";
   return 0;

} </source>

  • 메뉴 입력을 받아보자.

<source lang="c"> /* menu_chooser.cc */ // Menu menu_chooser // Demonstrates the switch statement

  1. include <iostream>

using namespace std;

int main() {

   cout << "Difficulty Levels\n\n";
   cout << "1 - Easy\n";
   cout << "2 - Normal\n";
   cout << "3 - Hard\n";
   int choice;
   cout << "Choice: ";
   cin >> choice;
   switch(choice)
   {
   case 1:
       cout << "You picked Easy.\n";
       break;
   case 2:
       cout << "You picked Normal.\n";
       break;
   case 3:
       cout << "You picked Hard.\n";
       break;
   default:
       cout << "You made an illegal choice.\n"
   }
   return 0;

} </source>

  • switch문 별거 없다.

Play Again

  • Play Again 루프를 돌려보자.

<source lang="c"> /* play_again.cc */ // Play Again // Demonstrates while loops

  1. include <iostream>

using namespace std;

int main() {

   char again = 'y';
   while(again == 'y')
   {
       cout << "\n** Played an exciting game **";
       cout << "\nDo you want to play again? (y/n): ";
       cin >> again;
   }
   cout << "\nOkay, bye.";
   return 0;

} </source>

  • do while로 좀더 직관적으로 해보자.

<source lang="c"> /* play_again2.cc */ // Play Again 2.0 // Demonstrates do loops

  1. include <iostream>

using namespace std;

int main() {

   char again;
   do
   {
       cout << "\n** Played an exciting game**";
       cout << "\nDo you want to play again? (y/n)";
       cin >> again;
   } while (again == 'y');
   cout << "\nOkay, bye.";
   return 0;

} </source>

  • 좀더 직관적이 되었다.

Counter

  • 다음은 break와 continue를 위한 카운터를 돌려보자.

<source lang="c"> /* finicky_counter.cc */ // Finicky Counter // Demonstrates break and continue statements

  1. include <iostream>

using namespace std;

int main() {

   int count = 0;
   while(true)
   {
       count += 1;
       // count가 10보다 크면 루프를 끝냄
       if(count > 10)
           break;
       // 5는 스킵
       if(count == 5)
           continue;
       cout << count << endl;
   }
   return 0;

} </source>

  • 이해를 돕기 위한 쓸모없는프로그램

Designers Network

<source lang="c"> /* designers_network.cc */ // Designers Network // Demonstrates logical operators

  1. include <iostream>
  2. include <string>

using namespace std;

int main() {

   cout << "\tGame Designer's Network\n";
   int security = 0;
   string username;
   cout << "\nUsername: ";
   cin >> username;
   string password;
   cout << "Password: ";
   cin >> password;
   if(username = "S.Meier" && password == "bar")
   {
       cout << "\nHey, Sid.":
       security = 5;
   }
   if(username = "S.Miyamoto" && password == "mariobros")
   {
       cout << "\nWhat's up, Shigeru?";
       security = 5;
   }
   if(username == "W.Wright" && password == "thesims")
   {
       cout << "\nHow goes it, Will?";
       security = 5;
   }
   if(username == "guest" || password == "guest")
   {
       cout << "\nWelcome, Guest.";
       security = 1;
   }
   if(!security)
       cout << "\nYour login failed.";
   return 0;

} </source>

  • 패스워드 처리는 이따위로 하면 안되겠지? ㅋㅋ

Die Roller

  • 한국어로 주사위.
  • 랜덤을 써보자

<source lang="c"> /* die_roller.cc */ // Die Roller// Demonstrates generating random numbers

  1. include <iostream>
  2. include <cstdlib>
  3. include <ctime>

using namespace std;

int main() {

   srand(time(0)); // 랜덤시드를 현재시간으로 설정
   int randomNumber = rand(); // 랜덤수 하나 뽑아옴
   int die = (randomNumber % 6) + 1; // 1부터 6까지 수 중에 하나
   cout << "You rolled a " << die << endl;
   return 0;

} </source>

  • 자, 게임에서 가장 중요한 랜덤뽑기다.
  • 초단위

Guess My Number

  • 일반적으로 대부분의 콘솔게임은 다음과 같은 진행으로 이루어진다.

파일:Game flow.png

  • 플로챠트 내용은 다음과 같다.
  1. Setting up - 보통, 초기 세팅을 하고 로딩하고 사운드, 그래픽을 활성화한다.
  2. Getting player input - 키보드, 마우스, 조이스틱, 트랙볼같은 디바이스로부터 플레이어 입력을 받는다.
  3. Updating game internals - 사용자 입력과 게임 로직(AI 포함)에 따라 게임 내부의 좌표 등의 업데이트를 한다.
  4. Updating display - 게임 프로그래밍이라고 하면 보통 이쪽을 많이 생각하는데, 실제 어려운건 위의 내용이다.
  5. Checking whether the game is over - 게임 로직에 따라, 게임 오버를 결정한다.
  6. Shutting down - 마지막으로 하이스코어 등의 정보를 사용자에게 보여주고 프로그램을 종료시키거나 새로 시작하거나 한다.
  • Guess My Number는 다음과 같은 순서로 이루어진다.

파일:Guess my number flow.png

<source lang="c"> /* guess_my_number.cc */ // Guess My Number // The classic number guessing game

  1. include <iostream>
  2. include <cstdlib>
  3. include <ctime>

using namespace std;

inat main() {

   srand(time(0)); // 랜덤시드를 현재기각으로.
   int theNumber = rand() % 100 + 1; // 1부터 100까지 숫자중에 하나
   int tries = 0, guess;
   cout << "\tWelcome to Guess My Number\n\n";
   do {
       cout << "Enter a guess: ";
       cin >> guess;
       ++tries;
       if(guess > theNumber)
           cout << "Too high!\n\n";
       if(guess < theNumber)
           cout << "Too low!\n\n";
   } while (guess != theNumber);
   cout << "\nThat's it! You got it in " << tries << " guesses!\n";
   return 0;

} </source>

Counter

  • 숫자를 앞으로 세고, 뒤로 세는 프로그램이다.별거 없는데 이름만 그럴싸한데

<source lang="c"> /* counter.cc */ // Counter // Demonstrates for loops

  1. include <iostream>

using namespace std;

int main() {

   cout << "Counting forward.\n";
   for(int i = 0; i < 10; ++i)
       cout << i << " ";
   cout << "\n\nCounting backward:\n":
   for(int i = 0; i >= 0; --i)
       cout << i << " ";
   cout << "\n\nCounting by fives:\n";
   for(int i = 0; i <= 50; i += 5)
       cout << i << " ";
   cout << "\n\nCounting with null statements:\n";
   int count = 0;
   for (; count < 10;)
   {
       cout << count << " ";
       ++count;
   }
   cout << "\n\nCounting with nested for loops:\n";
   const int ROWS = 5;
   const int COLUMNS = 3;
   for(int i = 0; i < ROWS; ++i)
   {
       for(int j = 0; j < COLUMNS; ++j)
           cout << i << "," << j << "  ";
       cout << endl;
   }
   return 0;

} </source>

String Tester

  • String에 대해서 좀 알아보자.

<source lang="c"> /* string_tester.cc */ // String Tester // Demonstrates string objects

  1. include <iostream>
  2. include <string>

using namespace std;

int main() {

   string word1 = "Game";
   string word2("Over");
   string word3(3, '!');
   string phrase = word1 + " " + word2 + word3;
   cout << "The phrase is: " << phrase << "\n\n";
   cout << "The phrase has " << phrase.size() << " characters in it.\n\n";
   cout << "The character at position 0 is: " << phrase[0] << "\n\n";
   cout << "Changing the character at position 0.\n";
   phrase[0] = 'L';
   cout << "The phrase is now: " << phrase << "\n\n";
   for(int i = 0; i < phrase.size(); ++i)
       cout << "Character at position " << i << " is: " << phrase[i] << endl;
   cout << "\nThe sequence 'Over' begins at location " << phrase.find("Over") << endl;
   if(phrase.find("eggplant") == string::npos)
       cout << "'eggplant' is not in the phrase.\n\n";
   phrase.erase(4, 5);
   cout << "The phrase is now: " << phrase << endl;
   phrase.erase(4);
   cout << "The phrase is now: " << phrase << endl;
   phrase.erase();
   cout << "The phrase is now: " << phrase << endl;
   if(phrase.empty())
       cout << "\nThe phrase is no more.\n";
   return 0;

} </source>

  • Ansi-C보다 문자열만 봐도 C++이 좀더 쓰기 쉽다그만큼 디버깅은 빡세지지

Hero's Inventory

  • 배열에 대한 이야기

<source lang="c"> /* heros_inventory.cc */ // Hero's Inventory // Demonstrates arrays

  1. include <iostream>
  2. include <string>

using namespace std;

int main() {

   const int MAX_ITEMS = 10;
   string inventory[MAX_ITEMS];
   int numItems = 0;
   inventory[numItems++] = "sword";
   inventory[numItems++] = "armor";
   inventory[numItems++] = "shield";
   cout << "Your items:\n";
   for(int i = 0; i < numItems; ++i)
       cout << inventory[i] << endl;
   cout << "\nYou trade your sword for a battle axe.";
   inventory[0] = "battle axe";
   cout << "\nYour items:\n";
   for(int i = 0; i < numItems; ++i)
       cout << inventory[i] << endl;
   cout << "\nThe Item name '" << inventory[0] << "' has ";
   cout << inventory[0].size() << " letters in it.\n";
   cout << "\nYou find a healing potion.";
   if(numItems < MAX_ITEMS)
       inventory[numItems++] = "healing potion";
   else
       cout << "You have too many items and can't carry another.";
   cout << "\nYour items:\n";
   for(int i = 0; i < numItems; ++i)
       cout << inventory[i] << endl;
   return 0;

} </source>

  • 배열에 대해 알아보았다.
  • 이제 2.0을 돌려보자.

<source lang="c"> /* heros_inventory2.cc */ // Hero's Inventory 2.0 // Demonstrates Vectors

  1. include <iostream>
  2. include <string>
  3. include <vector>

using namespace std;

int main() {

   vector<string> inventory;
   inventory.push_back("sword");
   inventory.push_back("armor");
   inventory.push_back("shield");
   cout << "You have " << inventory.size() << " items.\n";
   cout << "\nYour items:\n";
   for(int i = 0; i < inventory.size(); ++i)
       cout << inventory[i] << endl;
   cout << "\nYou trade your sword for a battle axe.";
   inventory[0] = "battle axe";
   cout << "\nYour items:\n";
   for(int i = 0; i < inventory.size(); ++i)
       cout << inventory[i] << endl;
   cout << "\nThe item name '" << inventory[0] << "' has ";
   cout << inventory[0].size() << " letters in it.\n";
   cout << "\nYour shield is destroyed in a fierce battle.";
   inventory.pop_back();
   cout << "\nYour items:\n";
   for(int i = 0; i < inventory.size(); ++i)
       cout << inventory[i] << endl;
   cout << "\nYou were robbed of all of your possessions by a thief.";
   inventory.clear();
   if(inventory.empty())
       cout << "\nYou have nothing.\n";
   else
       cout << "\nYou have at least one item.\n";
   return 0;

} </source>

  • C++의 강력한 기능중 하나인 벡터다.
  • 이제 이터레이터라는게 있다. 그걸로 좀더 향상된 3.0을 만들어보자.

<source lang="c"> /* heros_inventory3.cc */ // Hero's Inventory 3.0 // Demonstrates iterators

  1. include <iostream>
  2. include <string>
  3. include <vector>

using namespace std;

int main() {

   vector<string> inventory;
   inventory.push_back("sword");
   inventory.push_back("armor");
   inventory.push_back("shield");
   vector<string>::iterator myIterator;
   vector<string>::const_iterator iter;
   cout << "Your items:\n";
   for(iter = inventory.begin(); iter != inventory.end(); ++iter)
       cout << *iter << endl;
   cout << "\nYou trade your sword for a battle axe.";
   myIterator = inventory.begin();
   *myIterator = "battle axe";
   cout << "\nYour Items:\n";
   for(iter = inventory.begin(); iter != inventory.end(); ++iter)
       cout << *iter << endl;
   cout << "\nThe item name '" << *myIterator << "' has ";
   cout << (*myIterator).size() << " letters in it.\n";
   cout << "\nThe item name '" << *myIterator << "' has ";
   cout << myIterator->size() << " letters in it.\n";
   cout << "\nYou recover a crossbow from a slain enemy.";
   inventory.insert(inventory.begin(), "crossbow");
   cout << "\nYour items:\n";
   for(iter = inventory.begin(); iter != inventory.end(); ++iter)
       cout << *iter << endl;
   cout << "\nYour armor is destroyed in a fierce battle.";
   inventory.erase((inventory.begin() + 2));
   cout << "\nYour items:\n";
   for(iter = inventory.begin(); iter != inventory.end(); ++iter)
       cout << *iter << endl;
   return 0;

} </source>

  • 웬지 좀 더 복잡해진것 같지만, 좀 더 직관적이 되었다.
  • 명시적 표현은 항상 신경쓰는게 좋다.

Tic-Tac-Toe Board

  • 여러군데서 자주 나오는 틱탁토탁탁탁이 아니다 예제다.

<source lang="c"> /* tic-tac-toe_board.cc */ // Tic-Tac-Toe Board // Demonstrates multidimensional arrays

  1. include <iostream>

using namespace std;

int main() {

   const int ROWS = 3;
   const int COLUMNS = 3;
   char board[ROWS][COLUMNS] = {
       { 'O', 'X', 'O' },
       { ' ', 'X', 'X' },
       { 'X', 'O', 'O' }
   };
   cout << "Here's the tic-tac-toe board:\n";
   for(int i = 0; i < ROWS; ++i)
   {
       for(int j = 0; j < COLUMNS; ++j)
           cout << board[i][j];
       cout << endl;
   }
   cout << "\n'X' moves to the empty location.\n\n";
   board[1][0] = 'X';
   cout << "Now the tic-tac-toe board is:\n";
   for(int i = 0; i < ROWS; ++i)
   {
       for(int j = 0; j < COLUMNS; ++j)
           cout << board[i][j];
       cout << endl;
   }
   cout << "\n'X' wins!";
   return 0;

} </source>

  • 다른 책들보다 좀 허접한 느낌이 든다.
  • 뭐 어쨌거나 2차원배열에 대해서 약간 감이 왔으리라 생각한다.

Word Jumble

  • 단어 뒤섞기 게임이다.

<source lang="c"> // Word Jumble // The classic word jumble game where the player can ask for a hint

  1. include <iostream>
  2. include <string>
  3. include <cstdlib>
  4. include <ctime>

using anmespace std;

int main() {

   enum fields (WORD, HINT, NUM_FIELDS);
   const int NUM_WORDS = 5;
   const string WORDS[NUM_WORDS][NUM_FIELDS] =
   {
       {"wall", "Do you feel you're banging your head against something?"},
       {"glasses", "These might help you see the answer."},
       {"labored", "Going slowly, is it?"},
       {"persistent", "Keep at it."},
       {"jumble", "It's what the game is all about."}
   };
   
   string jumble = theWord;
   int length = jumble.size();
   for(int i = 0; i < length; ++i)
   {
       int index1 = (rand() % length);
       int index2 = (rand() % length);
       char temp = jumble[index1];
       jumble[index1] = jumble[index2];
       jumble[index2] = temp;
   }
   cout << "\t\tWelcome to Word Jumble!\n\n";
   cout << "Unscramble the letters to make a word.\n";
   cout << "Enter 'hint' for a hint.\n";
   cout << "Enter 'quit' for quit the game.\n\n";
   cout << "The jumble is: " << jumble;
   string guess;
   cout << "\n\nYour Guess: ";
   cin >> guess;
   while (( guess != theWord) && (guess !="quit"))
   {
       if(guess == "hint")
           cout << theHint;
       else
           cout << "Sorry, that's not it.";
       cout << "\n\nYour guess: ";
       cin >> guess;
   }
   if(guess == theWord)
       cout << "\nThat's it! You guessed it!\n";
   cout << "\nThanks for playing.\n";
   return 0;

} </source>

  • 아주 기초적이고 재미도 없다.
  • 하지만, 한번 해본것과 안 해본것은 엄청난 차이가 있다.

High Scores

  • 알고리즘 표현법을 알아보기 위해 하이스코어 보드를 만들어 보자.

<source lang="c"> /* high_scores.cc */ // High Scores // Demonstrates algorithms

  1. include <iostream>
  2. include <vector>
  3. include <algorithm>
  4. include <ctime>
  5. include <cstdlib>

using namespace std;

int main() {

   vector<int>::const_iterator iter;
   cout << "Creating a list of scores.";
   vector<int> scores;
   scores.push_back(1500);
   scores.push_back(3500);
   scores.push_back(7500);
   cout << "\nHigh Scores:\n";
   for(iter = scores.begin(); iter != scores.end(); ++iter)
       cout << *iter << endl;
   cout << "\nRandomizing scores.";
   srand(time(0));
   random_shuffle(scores.begin(), score.end());
   cout << "\nHigh Scores:\n";
   for(iter = scores.begin(); iter != scores.end(); ++iter)
       cout << *iter << endl;
   cout << "\nSorting scores.";
   sort(scores.begin(), scores.end());
   cout << "\nHigh Scores:\n";
   for(iter = scores.begin(); iter != scores.end(); ++iter)
       cout << *iter << endl;
   cout << "\nCreating another list of scores.";
   vector<int> moreScores;
   moreScores.push_back(2000);
   moreScores.push_back(4000);
   moreScores.push_back(8000);
   cout << "\nMore High Scores:\n";
   for(iter = moreScores.begin(); iter != moreScores.end(); ++iter)
       cout << *iter << endl;
   cout << "\nMerging both lists.";
   vector<int> allScores(6); // 결과를 저장하기 위해 충분히 큰 공간 할당
   merge(scores.begin(), scores.end(), moreScores.begin(), moreScores.end(), allScores.begin());
   cout << "\nAll High Scores:\n";
   for(iter = allScores.begin(); iter != allScores.end(); ++iter)
       cout << *iter << endl;
   return 0;

} </source>

  • Ansi-C를 하던 사람이라면, 살짝 보기 힘든 코드다.