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 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. #include "logic.h"
  2. #include "structures.h"
  3. #include <grpcpp/grpcpp.h>
  4. #include <functional>
  5. #include "utils.hpp"
  6. #include "Communication.h"
  7. extern const bool asynchronous;
  8. extern const THUAI6::PlayerType playerType;
  9. Logic::Logic(THUAI6::PlayerType type, int64_t ID, THUAI6::ButcherType butcher, THUAI6::HumanType human) :
  10. playerType(type),
  11. playerID(ID),
  12. butcherType(butcher),
  13. humanType(human)
  14. {
  15. currentState = &state[0];
  16. bufferState = &state[1];
  17. }
  18. std::vector<std::shared_ptr<const THUAI6::Butcher>> Logic::GetButchers() const
  19. {
  20. std::lock_guard<std::mutex> lock(mtxBuffer);
  21. std::vector<std::shared_ptr<const THUAI6::Butcher>> temp;
  22. temp.assign(currentState->butchers.begin(), currentState->butchers.end());
  23. return temp;
  24. }
  25. std::vector<std::shared_ptr<const THUAI6::Human>> Logic::GetHumans() const
  26. {
  27. std::unique_lock<std::mutex> lock(mtxBuffer);
  28. std::vector<std::shared_ptr<const THUAI6::Human>> temp;
  29. temp.assign(currentState->humans.begin(), currentState->humans.end());
  30. return temp;
  31. }
  32. std::vector<std::shared_ptr<const THUAI6::Prop>> Logic::GetProps() const
  33. {
  34. std::unique_lock<std::mutex> lock(mtxBuffer);
  35. std::vector<std::shared_ptr<const THUAI6::Prop>> temp;
  36. temp.assign(currentState->props.begin(), currentState->props.end());
  37. return temp;
  38. }
  39. std::shared_ptr<const THUAI6::Human> Logic::HumanGetSelfInfo() const
  40. {
  41. std::unique_lock<std::mutex> lock(mtxBuffer);
  42. return currentState->humanSelf;
  43. }
  44. std::shared_ptr<const THUAI6::Butcher> Logic::ButcherGetSelfInfo() const
  45. {
  46. std::unique_lock<std::mutex> lock(mtxBuffer);
  47. return currentState->butcherSelf;
  48. }
  49. std::vector<std::vector<THUAI6::PlaceType>> Logic::GetFullMap() const
  50. {
  51. std::unique_lock<std::mutex> lock(mtxBuffer);
  52. return currentState->gamemap;
  53. }
  54. THUAI6::PlaceType Logic::GetPlaceType(int32_t CellX, int32_t CellY) const
  55. {
  56. std::unique_lock<std::mutex> lock(mtxBuffer);
  57. return currentState->gamemap[CellX][CellY];
  58. }
  59. bool Logic::Move(int64_t time, double angle)
  60. {
  61. return pComm->Move(time, angle, playerID);
  62. }
  63. bool Logic::PickProp(THUAI6::PropType prop)
  64. {
  65. return pComm->PickProp(prop, playerID);
  66. }
  67. bool Logic::UseProp()
  68. {
  69. return pComm->UseProp(playerID);
  70. }
  71. bool Logic::UseSkill()
  72. {
  73. return pComm->UseSkill(playerID);
  74. }
  75. bool Logic::SendMessage(int64_t toID, std::string message)
  76. {
  77. return pComm->SendMessage(toID, message, playerID);
  78. }
  79. bool Logic::HaveMessage()
  80. {
  81. return pComm->HaveMessage();
  82. }
  83. std::optional<std::pair<int64_t, std::string>> Logic::GetMessage()
  84. {
  85. return pComm->GetMessage();
  86. }
  87. bool Logic::Escape()
  88. {
  89. return pComm->Escape(playerID);
  90. }
  91. bool Logic::StartFixMachine()
  92. {
  93. return pComm->StartFixMachine(playerID);
  94. }
  95. bool Logic::EndFixMachine()
  96. {
  97. return pComm->EndFixMachine(playerID);
  98. }
  99. bool Logic::StartSaveHuman()
  100. {
  101. return pComm->StartSaveHuman(playerID);
  102. }
  103. bool Logic::EndSaveHuman()
  104. {
  105. return pComm->EndSaveHuman(playerID);
  106. }
  107. bool Logic::Attack(double angle)
  108. {
  109. return pComm->Attack(angle, playerID);
  110. }
  111. bool Logic::CarryHuman()
  112. {
  113. return pComm->CarryHuman(playerID);
  114. }
  115. bool Logic::ReleaseHuman()
  116. {
  117. return pComm->ReleaseHuman(playerID);
  118. }
  119. bool Logic::HangHuman()
  120. {
  121. return pComm->HangHuman(playerID);
  122. }
  123. bool Logic::WaitThread()
  124. {
  125. Update();
  126. return true;
  127. }
  128. void Logic::ProcessMessage()
  129. {
  130. auto messageThread = [&]()
  131. {
  132. std::cout << "Join Player!" << std::endl;
  133. pComm->AddPlayer(playerID, playerType, humanType, butcherType);
  134. while (gameState != THUAI6::GameState::GameEnd)
  135. {
  136. if (pComm->HaveMessage2Client())
  137. {
  138. std::cout << "Get Message!" << std::endl;
  139. auto clientMsg = pComm->GetMessage2Client();
  140. gameState = Proto2THUAI6::gameStateDict[clientMsg.game_state()];
  141. switch (gameState)
  142. {
  143. case THUAI6::GameState::GameStart:
  144. std::cout << "Game Start!" << std::endl;
  145. // 重新读取玩家的guid,guid确保人类在前屠夫在后
  146. playerGUIDs.clear();
  147. for (auto human : clientMsg.human_message())
  148. playerGUIDs.push_back(human.guid());
  149. for (auto butcher : clientMsg.butcher_message())
  150. playerGUIDs.push_back(butcher.guid());
  151. currentState->guids = playerGUIDs;
  152. bufferState->guids = playerGUIDs;
  153. LoadBuffer(clientMsg);
  154. AILoop = true;
  155. UnBlockAI();
  156. break;
  157. case THUAI6::GameState::GameRunning:
  158. // 重新读取玩家的guid,guid确保人类在前屠夫在后
  159. playerGUIDs.clear();
  160. for (auto human : clientMsg.human_message())
  161. playerGUIDs.push_back(human.guid());
  162. for (auto butcher : clientMsg.butcher_message())
  163. playerGUIDs.push_back(butcher.guid());
  164. currentState->guids = playerGUIDs;
  165. bufferState->guids = playerGUIDs;
  166. LoadBuffer(clientMsg);
  167. break;
  168. case THUAI6::GameState::GameEnd:
  169. AILoop = false;
  170. {
  171. std::lock_guard<std::mutex> lock(mtxBuffer);
  172. bufferUpdated = true;
  173. counterBuffer = -1;
  174. }
  175. cvBuffer.notify_one();
  176. std::cout << "Game End!" << std::endl;
  177. break;
  178. default:
  179. std::cerr << "Invalid GameState!" << std::endl;
  180. }
  181. }
  182. }
  183. };
  184. std::thread(messageThread).detach();
  185. }
  186. void Logic::LoadBuffer(protobuf::MessageToClient& message)
  187. {
  188. // 将消息读入到buffer中
  189. {
  190. std::lock_guard<std::mutex> lock(mtxBuffer);
  191. // 清空原有信息
  192. bufferState->humans.clear();
  193. bufferState->butchers.clear();
  194. bufferState->props.clear();
  195. std::cout << "Buffer clear!" << std::endl;
  196. // 读取新的信息
  197. // 读取消息的选择待补充,之后需要另外判断;具体做法应该是先读到自己,然后按照自己的视野做处理。此处暂时全部读了进来
  198. bufferState->gamemap = Proto2THUAI6::Protobuf2THUAI6Map(message.map_message());
  199. if (playerType == THUAI6::PlayerType::HumanPlayer)
  200. {
  201. for (const auto& item : message.human_message())
  202. {
  203. if (item.player_id() == playerID)
  204. {
  205. bufferState->humanSelf = Proto2THUAI6::Protobuf2THUAI6Human(item);
  206. }
  207. bufferState->humans.push_back(Proto2THUAI6::Protobuf2THUAI6Human(item));
  208. }
  209. for (const auto& item : message.butcher_message())
  210. {
  211. int vr = this->bufferState->humanSelf->viewRange;
  212. int deltaX = item.x() - this->bufferState->humanSelf->x;
  213. int deltaY = item.y() - this->bufferState->humanSelf->y;
  214. double distance = deltaX * deltaX + deltaY * deltaY;
  215. if (distance > vr * vr)
  216. continue;
  217. else
  218. {
  219. int divide = abs(deltaX) > abs(deltaY) ? abs(deltaX) : abs(deltaY);
  220. divide /= 100;
  221. double dx = deltaX / divide;
  222. double dy = deltaY / divide;
  223. double myX = this->bufferState->humanSelf->x;
  224. double myY = this->bufferState->humanSelf->y;
  225. bool barrier = false;
  226. for (int i = 0; i < divide; i++)
  227. {
  228. myX += dx;
  229. myY += dy;
  230. if (this->bufferState->gamemap[IAPI::GridToCell(myX)][IAPI::GridToCell(myY)] == THUAI6::PlaceType::Wall)
  231. {
  232. barrier = true;
  233. break;
  234. }
  235. }
  236. if (barrier)
  237. continue;
  238. bufferState->butchers.push_back(Proto2THUAI6::Protobuf2THUAI6Butcher(item));
  239. std::cout << "Add Butcher!" << std::endl;
  240. }
  241. }
  242. }
  243. else
  244. {
  245. for (const auto& item : message.butcher_message())
  246. {
  247. if (item.player_id() == playerID)
  248. {
  249. bufferState->butcherSelf = Proto2THUAI6::Protobuf2THUAI6Butcher(item);
  250. }
  251. bufferState->butchers.push_back(Proto2THUAI6::Protobuf2THUAI6Butcher(item));
  252. }
  253. for (const auto& item : message.human_message())
  254. {
  255. int vr = this->bufferState->butcherSelf->viewRange;
  256. int deltaX = item.x() - this->bufferState->butcherSelf->x;
  257. int deltaY = item.y() - this->bufferState->butcherSelf->y;
  258. double distance = deltaX * deltaX + deltaY * deltaY;
  259. if (distance > vr * vr)
  260. continue;
  261. else
  262. {
  263. int divide = abs(deltaX) > abs(deltaY) ? abs(deltaX) : abs(deltaY);
  264. divide /= 100;
  265. double dx = deltaX / divide;
  266. double dy = deltaY / divide;
  267. double myX = this->bufferState->butcherSelf->x;
  268. double myY = this->bufferState->butcherSelf->y;
  269. bool barrier = false;
  270. for (int i = 0; i < divide; i++)
  271. {
  272. myX += dx;
  273. myY += dy;
  274. if (this->bufferState->gamemap[IAPI::GridToCell(myX)][IAPI::GridToCell(myY)] == THUAI6::PlaceType::Wall)
  275. {
  276. barrier = true;
  277. break;
  278. }
  279. }
  280. if (barrier)
  281. continue;
  282. bufferState->humans.push_back(Proto2THUAI6::Protobuf2THUAI6Human(item));
  283. std::cout << "Add Human!" << std::endl;
  284. }
  285. }
  286. }
  287. for (const auto& item : message.prop_message())
  288. bufferState->props.push_back(Proto2THUAI6::Protobuf2THUAI6Prop(item));
  289. if (asynchronous)
  290. {
  291. {
  292. std::lock_guard<std::mutex> lock(mtxState);
  293. std::swap(currentState, bufferState);
  294. }
  295. freshed = true;
  296. }
  297. else
  298. bufferUpdated = true;
  299. counterBuffer++;
  300. }
  301. // 唤醒其他线程
  302. cvBuffer.notify_one();
  303. }
  304. void Logic::Update() noexcept
  305. {
  306. if (!asynchronous)
  307. {
  308. std::unique_lock<std::mutex> lock(mtxBuffer);
  309. // 缓冲区被更新之后才可以使用
  310. cvBuffer.wait(lock, [&]()
  311. { return bufferUpdated; });
  312. std::swap(currentState, bufferState);
  313. bufferUpdated = false;
  314. counterState = counterBuffer;
  315. }
  316. }
  317. void Logic::Wait() noexcept
  318. {
  319. freshed = false;
  320. {
  321. std::unique_lock<std::mutex> lock(mtxBuffer);
  322. cvBuffer.wait(lock, [&]()
  323. { return freshed.load(); });
  324. }
  325. }
  326. void Logic::UnBlockAI()
  327. {
  328. {
  329. std::lock_guard<std::mutex> lock(mtxAI);
  330. AIStart = true;
  331. }
  332. cvAI.notify_one();
  333. }
  334. void Logic::UnBlockBuffer()
  335. {
  336. {
  337. std::lock_guard<std::mutex> lock(mtxBuffer);
  338. bufferUpdated = true;
  339. }
  340. cvBuffer.notify_one();
  341. }
  342. int Logic::GetCounter() const
  343. {
  344. std::unique_lock<std::mutex> lock(mtxState);
  345. return counterState;
  346. }
  347. const std::vector<int64_t> Logic::GetPlayerGUIDs() const
  348. {
  349. std::unique_lock<std::mutex> lock(mtxState);
  350. return currentState->guids;
  351. }
  352. bool Logic::TryConnection()
  353. {
  354. std::cout << "Trying to connect to server..." << std::endl;
  355. bool result = pComm->TryConnection(playerID);
  356. return result;
  357. }
  358. void Logic::Main(CreateAIFunc createAI, std::string IP, std::string port, bool level, std::string filename)
  359. {
  360. // 建立与服务器之间通信的组件
  361. pComm = std::make_unique<Communication>(IP, port);
  362. // 构造timer
  363. if (playerType == THUAI6::PlayerType::HumanPlayer)
  364. timer = std::make_unique<HumanAPI>(*this);
  365. else if (playerType == THUAI6::PlayerType::ButcherPlayer)
  366. timer = std::make_unique<ButcherAPI>(*this);
  367. // 构造AI线程
  368. auto AIThread = [&]()
  369. {
  370. {
  371. std::unique_lock<std::mutex> lock(mtxAI);
  372. cvAI.wait(lock, [this]()
  373. { return AIStart; });
  374. }
  375. auto ai = createAI();
  376. while (AILoop)
  377. {
  378. if (asynchronous)
  379. {
  380. Wait();
  381. timer->StartTimer();
  382. timer->Play(*ai);
  383. timer->EndTimer();
  384. }
  385. else
  386. {
  387. Update();
  388. timer->StartTimer();
  389. timer->Play(*ai);
  390. timer->EndTimer();
  391. }
  392. }
  393. };
  394. tAI = std::thread(AIThread);
  395. // 连接服务器
  396. if (TryConnection())
  397. {
  398. std::cout << "Connect to the server successfully, AI thread will be start." << std::endl;
  399. if (tAI.joinable())
  400. {
  401. std::cout << "Join the AI thread." << std::endl;
  402. // 首先开启处理消息的线程
  403. ProcessMessage();
  404. tAI.join();
  405. }
  406. }
  407. else
  408. {
  409. std::cout << "Connection error!" << std::endl;
  410. return;
  411. }
  412. }