Turbo-C
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
터보-C 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
Lua 게시판
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C/C++ Q/A
[2561] STL로 만든 Hangman 게임 소스
김백일.cedar [cedar] 1138 읽음    2003-05-05 20:41
ㅠ_ㅠ 님이 쓰신 글 :
: 행맨하는 프로그램을 작성하는건데 이 게임에서는 하나의 단어를 숨겨두고서 단지 그 단어의 길이만큼 밑줄을 화면에 표시한후, 사용자는 영문자를 입력함으로써 그 단어를 맞춰야 한다. 사용자가 하나의 문자를 입력할때마다, 숨겨진 단어에 그 문자가 포함되어 있는지를 확인한다. 만약 포함되어 있으면, 그 문자를 화면에 보여준다. 그 단어를 완전히 알아 맞출때까지 입력된 문자들의 수를 센다. 프로그램을 간단히 하기 위해 15번 이하의 시행에서 단어를 알아맞추면 이긴것으로 간주하여라.. 숨겨진 단어로 concatenation을 사용하여라.. 행맨그림은 문자로 만들라는데 어떻게 하는질 모르겠어요..ㅠ_ㅠ


크크... 오늘도 초보들을 괴롭히기 위한 STL 코드를 올립니다.

행맨을 구현하는 핵심 알고리듬은 간단합니다.
숨겨진 단어와 출력용 문자열을 만들어 놓고, 숨겨진 단어에서 입력 받은 문자를 찾아서,
그 위치의 문자와 출력용 문자('_')를 바꿔치기 하면 됩니다.

이것을 위해 swap_ranges의 조건 판단 버전인 swap_ranges_if 알고리듬을 만들었습니다.
물론 원래의 알고리듬에 if (pred(*first1)) 만 추가하면 되지요.

다음은, 이렇게 사용자 정의한 알고리듬에 사용된 while을 제외하고는
전혀 for 등의 루프를 사용하지 않은 버전입니다.

main()은 find_if 알고리듬을 써서 Hangman::operator()를 호출하는 것 뿐입니다.
즉, 대부분의 코드는 Hangman 클래스의 operator() 안에만 들어있습니다.

//---------------------------------------------------------------------------
#include <iostream>
#include <string>
#pragma hdrstop
#include <iterator>
#include <functional>
#include <algorithm>
//---------------------------------------------------------------------------

namespace mystd {
    template <typename ForwardIter1, typename ForwardIter2, typename Predicate>
    ForwardIter2
    swap_ranges_if(ForwardIter1 first1, ForwardIter1 last1,
                   ForwardIter2 first2, Predicate pred)
    {
      while (first1 != last1) {
        if (pred(*first1)) std::swap(*first1, *first2);
        ++first1; ++first2;
      }
      return first2;
    }
};

class Hangman : public std::unary_function<char, bool>
{
public:
    Hangman(std::string hidden_word, const int max_trial):
        hword(hidden_word), output(hidden_word.size(), unknown),
        num_trial(1), maxt(max_trial)
    { std::cout << "Trial 1 >> "; }

    bool operator()(char guess)
    {
        mystd::swap_ranges_if(hword.begin(), hword.end(),
            output.begin(), std::bind2nd(std::equal_to<char>(), guess));
        std::cout << output << std::endl;

        bool solved =
            (std::find(output.begin(), output.end(), unknown) == output.end()),
             failed = (++num_trial >= maxt);

        if (solved)
            std::cout << "Solved!\n";
        else if (failed)
            std::cout << "Failed\n";
        else
            std::cout << "Trial " << num_trial << ">> ";

        return solved || failed;
    }
private:
    std::string hword, output;
    int num_trial, maxt;
    static const char unknown;
};

const char Hangman::unknown = '_';

int main()
{
    using namespace std;

    const string sample_word = "concatenation";
    const int max_trial = 15;
    find_if(istream_iterator<char>(cin), istream_iterator<char>(),
            Hangman(sample_word, max_trial));

    return 0;
}
//---------------------------------------------------------------------------

+ -

관련 글 리스트
2558 도와주세요..ㅠ_ㅠ ㅠ_ㅠ 870 2003/05/05
2561     STL로 만든 Hangman 게임 소스 김백일.cedar 1138 2003/05/05
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.