dice_game.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright Keld Helsgaun 2000, Oliver Kowalke 2014.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/coroutine/all.hpp>
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <boost/bind.hpp>
  9. #include <boost/move/move.hpp>
  10. #include <boost/random/random_device.hpp>
  11. #include <boost/random/uniform_int_distribution.hpp>
  12. typedef boost::coroutines::symmetric_coroutine< void > coro_t;
  13. class player
  14. {
  15. private:
  16. int die()
  17. {
  18. boost::random::uniform_int_distribution<> dist( 1, 6);
  19. return dist( gen);
  20. }
  21. void run_( coro_t::yield_type & yield)
  22. {
  23. int sum = 0;
  24. while ( ( sum += die() ) < 100)
  25. yield( nxt->coro);
  26. std::cout << "player " << id << " winns" << std::endl;
  27. }
  28. player( player const&);
  29. player & operator=( player const&);
  30. public:
  31. int id;
  32. player * nxt;
  33. coro_t::call_type coro;
  34. boost::random::random_device gen;
  35. player( int id_) :
  36. id( id_), nxt( 0),
  37. coro( boost::bind( & player::run_, this, _1) ),
  38. gen()
  39. {}
  40. void run()
  41. { coro(); }
  42. };
  43. int main( int argc, char * argv[])
  44. {
  45. player * first = new player( 1);
  46. player * p = first;
  47. for ( int i = 2; i <= 4; ++i)
  48. {
  49. p->nxt = new player( i);
  50. p = p->nxt;
  51. }
  52. p->nxt = first;
  53. first->run();
  54. std::cout << "Done" << std::endl;
  55. return EXIT_SUCCESS;
  56. }