You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

logic.cpp 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "logic.h"
  2. #include "structures.h"
  3. #include <grpcpp/grpcpp.h>
  4. #include <functional>
  5. using namespace protobuf;
  6. using grpc::ClientContext;
  7. extern const THUAI6::PlayerType playerType;
  8. Logic::Logic(THUAI6::PlayerType type, int ID, THUAI6::ButcherType butcher, THUAI6::HumanType human) :
  9. playerType(type),
  10. playerID(ID),
  11. butcherType(butcher),
  12. humanType(human)
  13. {
  14. currentState = &state[0];
  15. bufferState = &state[1];
  16. }
  17. protobuf::MessageToClient Logic::GetFullMessage()
  18. {
  19. }
  20. void Logic::Update() noexcept
  21. {
  22. }
  23. void Logic::PlayerWrapper(std::function<void()> player)
  24. {
  25. {
  26. std::unique_lock<std::mutex> lock(mtxAI);
  27. cvAI.wait(lock, [this]()
  28. { return AIStart; });
  29. }
  30. player();
  31. }
  32. bool Logic::TryConnection()
  33. {
  34. IDMsg request;
  35. BoolRes reply;
  36. ClientContext context;
  37. request.set_player_id(playerID);
  38. auto status = THUAI6Stub->TryConnection(&context, request, &reply);
  39. if (status.ok())
  40. return true;
  41. else
  42. return false;
  43. }
  44. void Logic::Main(CreateAIFunc createAI, std::string IP, std::string port)
  45. {
  46. // 构造AI
  47. pAI = createAI();
  48. // 建立与服务器之间通信的Stub
  49. std::string aim = IP + ':' + port;
  50. auto channel = grpc::CreateChannel(aim, grpc::InsecureChannelCredentials());
  51. THUAI6Stub = protobuf::AvailableService::NewStub(channel);
  52. // 构造timer
  53. if (playerType == THUAI6::PlayerType::HumanPlayer)
  54. timer = std::make_unique<HumanAPI>(*this);
  55. else if (playerType == THUAI6::PlayerType::ButcherPlayer)
  56. timer = std::make_unique<ButcherAPI>(*this);
  57. // 构造AI线程
  58. auto AIThread = [&, this]()
  59. {
  60. auto ai = createAI();
  61. while (AILoop)
  62. {
  63. Update();
  64. timer->StartTimer();
  65. timer->Play(*ai);
  66. timer->EndTimer();
  67. }
  68. };
  69. tAI = std::thread(&Logic::PlayerWrapper, this, AIThread);
  70. // 连接服务器
  71. if (TryConnection())
  72. {
  73. std::cout << "Connect to the server successfully, AI thread will be start." << std::endl;
  74. if (tAI.joinable())
  75. {
  76. std::cout << "Join the AI thread." << std::endl;
  77. tAI.join();
  78. }
  79. }
  80. else
  81. {
  82. std::cout << "Connection error!" << std::endl;
  83. }
  84. }