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.py 28 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import os
  2. from typing import List, Union, Callable, Tuple
  3. import threading
  4. import logging
  5. import copy
  6. import platform
  7. import proto.MessageType_pb2 as MessageType
  8. import proto.Message2Server_pb2 as Message2Server
  9. import proto.Message2Clients_pb2 as Message2Clients
  10. from queue import Queue
  11. import PyAPI.structures as THUAI6
  12. from PyAPI.utils import Proto2THUAI6, AssistFunction
  13. from PyAPI.DebugAPI import StudentDebugAPI, TrickerDebugAPI
  14. from PyAPI.API import StudentAPI, TrickerAPI
  15. from PyAPI.AI import Setting
  16. from PyAPI.Communication import Communication
  17. from PyAPI.State import State
  18. from PyAPI.Interface import ILogic, IGameTimer
  19. class Logic(ILogic):
  20. def __init__(self, playerID: int, playerType: THUAI6.PlayerType) -> None:
  21. # ID
  22. self.__playerID: int = playerID
  23. self.__playerType: THUAI6.PlayerType = playerType
  24. # 通信
  25. self.__comm: Communication
  26. # 存储状态
  27. self.__currentState: State = State()
  28. self.__bufferState: State = State()
  29. # timer,用于实际运行AI
  30. self.__timer: IGameTimer
  31. # AI线程
  32. self.__threadAI: threading.Thread
  33. # 互斥锁
  34. self.__mtxState: threading.Lock = threading.Lock()
  35. # 条件变量
  36. self.__cvBuffer: threading.Condition = threading.Condition()
  37. self.__cvAI: threading.Condition = threading.Condition()
  38. # 保存缓冲区数
  39. self.__counterState: int = 0
  40. self.__counterBuffer: int = 0
  41. # 记录游戏状态
  42. self.__gameState: THUAI6.GameState = THUAI6.GameState.NullGameState
  43. # 是否应该执行player()
  44. self.__AILoop: bool = True
  45. # buffer是否更新完毕
  46. self.__bufferUpdated: bool = False
  47. # 是否应当启动AI
  48. self.__AIStart: bool = False
  49. # asynchronous为True时控制内容更新的变量
  50. self.__freshed: bool = False
  51. self.__logger: logging.Logger = logging.getLogger("logic")
  52. self.__messageQueue: Queue = Queue()
  53. # IAPI统一可用的接口
  54. def GetTrickers(self) -> List[THUAI6.Tricker]:
  55. with self.__mtxState:
  56. self.__logger.debug("Called GetTrickers")
  57. return copy.deepcopy(self.__currentState.trickers)
  58. def GetStudents(self) -> List[THUAI6.Student]:
  59. with self.__mtxState:
  60. self.__logger.debug("Called GetStudents")
  61. return copy.deepcopy(self.__currentState.students)
  62. def GetProps(self) -> List[THUAI6.Prop]:
  63. with self.__mtxState:
  64. self.__logger.debug("Called GetProps")
  65. return copy.deepcopy(self.__currentState.props)
  66. def GetBullets(self) -> List[THUAI6.Bullet]:
  67. with self.__mtxState:
  68. self.__logger.debug("Called GetBullets")
  69. return copy.deepcopy(self.__currentState.bullets)
  70. def GetSelfInfo(self) -> Union[THUAI6.Student, THUAI6.Tricker]:
  71. with self.__mtxState:
  72. self.__logger.debug("Called GetSelfInfo")
  73. return copy.deepcopy(self.__currentState.self)
  74. def GetFullMap(self) -> List[List[THUAI6.PlaceType]]:
  75. with self.__mtxState:
  76. self.__logger.debug("Called GetFullMap")
  77. return copy.deepcopy(self.__currentState.gameMap)
  78. def GetPlaceType(self, x: int, y: int) -> THUAI6.PlaceType:
  79. with self.__mtxState:
  80. if x < 0 or x >= len(self.__currentState.gameMap) or y < 0 or y >= len(self.__currentState.gameMap[0]):
  81. self.__logger.warning("Invalid position")
  82. return THUAI6.PlaceType.NullPlaceType
  83. self.__logger.debug("Called GetPlaceType")
  84. return copy.deepcopy(self.__currentState.gameMap[x][y])
  85. def IsDoorOpen(self, x: int, y: int) -> bool:
  86. with self.__mtxState:
  87. self.__logger.debug("Called IsDoorOpen")
  88. if (x, y) in self.__currentState.mapInfo.doorState:
  89. return copy.deepcopy(self.__currentState.mapInfo.doorState[(x, y)])
  90. else:
  91. self.__logger.warning("Door not found")
  92. return False
  93. def GetClassroomProgress(self, x: int, y: int) -> int:
  94. with self.__mtxState:
  95. self.__logger.debug("Called GetClassroomProgress")
  96. if (x, y) in self.__currentState.mapInfo.classroomState:
  97. return copy.deepcopy(self.__currentState.mapInfo.classroomState[(x, y)])
  98. else:
  99. self.__logger.warning("Classroom not found")
  100. return -1
  101. def GetChestProgress(self, x: int, y: int) -> int:
  102. with self.__mtxState:
  103. self.__logger.debug("Called GetChestProgress")
  104. if (x, y) in self.__currentState.mapInfo.chestState:
  105. return copy.deepcopy(self.__currentState.mapInfo.chestState[(x, y)])
  106. else:
  107. self.__logger.warning("Chest not found")
  108. return -1
  109. def GetGateProgress(self, x: int, y: int) -> int:
  110. with self.__mtxState:
  111. self.__logger.debug("Called GetGateProgress")
  112. if (x, y) in self.__currentState.mapInfo.gateState:
  113. return copy.deepcopy(self.__currentState.mapInfo.gateState[(x, y)])
  114. else:
  115. self.__logger.warning("Gate not found")
  116. return -1
  117. def GetHiddenGateState(self, x: int, y: int) -> THUAI6.HiddenGateState:
  118. with self.__mtxState:
  119. self.__logger.debug("Called GetHiddenGateState")
  120. if (x, y) in self.__currentState.mapInfo.hiddenGateState:
  121. return copy.deepcopy(self.__currentState.mapInfo.hiddenGateState[(x, y)])
  122. else:
  123. self.__logger.warning("HiddenGate not found")
  124. return THUAI6.HiddenGateState.Null
  125. def GetDoorProgress(self, x: int, y: int) -> int:
  126. with self.__mtxState:
  127. self.__logger.debug("Called GetDoorProgress")
  128. if (x, y) in self.__currentState.mapInfo.doorProgress:
  129. return copy.deepcopy(self.__currentState.mapInfo.doorProgress[(x, y)])
  130. else:
  131. self.__logger.warning("Door not found")
  132. return -1
  133. def GetGameInfo(self) -> THUAI6.GameInfo:
  134. with self.__mtxState:
  135. self.__logger.debug("Called GetGameInfo")
  136. return copy.deepcopy(self.__currentState.gameInfo)
  137. def Move(self, time: int, angle: float) -> bool:
  138. self.__logger.debug("Called Move")
  139. return self.__comm.Move(time, angle, self.__playerID)
  140. def PickProp(self, propType: THUAI6.PropType) -> bool:
  141. self.__logger.debug("Called PickProp")
  142. return self.__comm.PickProp(propType, self.__playerID)
  143. def UseProp(self, propType: THUAI6.PropType) -> bool:
  144. self.__logger.debug("Called UseProp")
  145. return self.__comm.UseProp(propType, self.__playerID)
  146. def ThrowProp(self, propType: THUAI6.PropType) -> bool:
  147. self.__logger.debug("Called ThrowProp")
  148. return self.__comm.ThrowProp(propType, self.__playerID)
  149. def UseSkill(self, skillID: int) -> bool:
  150. self.__logger.debug("Called UseSkill")
  151. return self.__comm.UseSkill(skillID, self.__playerID)
  152. def SendMessage(self, toID: int, message: Union[str, bytes]) -> bool:
  153. self.__logger.debug("Called SendMessage")
  154. return self.__comm.SendMessage(toID, message, self.__playerID)
  155. def HaveMessage(self) -> bool:
  156. self.__logger.debug("Called HaveMessage")
  157. return not self.__messageQueue.empty()
  158. def GetMessage(self) -> Tuple[int, Union[str, bytes]]:
  159. self.__logger.debug("Called GetMessage")
  160. if self.__messageQueue.empty():
  161. self.__logger.warning("Message queue is empty!")
  162. return -1, ""
  163. else:
  164. return self.__messageQueue.get()
  165. def WaitThread(self) -> bool:
  166. self.__Update()
  167. return True
  168. def GetCounter(self) -> int:
  169. with self.__mtxState:
  170. return copy.deepcopy(self.__counterState)
  171. def GetPlayerGUIDs(self) -> List[int]:
  172. with self.__mtxState:
  173. return copy.deepcopy(self.__currentState.guids)
  174. # IStudentAPI使用的接口
  175. def Graduate(self) -> bool:
  176. self.__logger.debug("Called Graduate")
  177. return self.__comm.Graduate(self.__playerID)
  178. def StartLearning(self) -> bool:
  179. self.__logger.debug("Called StartLearning")
  180. return self.__comm.StartLearning(self.__playerID)
  181. def StartEncourageMate(self, mateID: int) -> bool:
  182. self.__logger.debug("Called StartEncourageMate")
  183. return self.__comm.StartEncourageMate(self.__playerID, mateID)
  184. def StartRouseMate(self, mateID: int) -> bool:
  185. self.__logger.debug("Called StartRouseMate")
  186. return self.__comm.StartRouseMate(self.__playerID, mateID)
  187. def Attack(self, angle: float) -> bool:
  188. self.__logger.debug("Called Trick")
  189. return self.__comm.Attack(angle, self.__playerID)
  190. def CloseDoor(self) -> bool:
  191. self.__logger.debug("Called CloseDoor")
  192. return self.__comm.CloseDoor(self.__playerID)
  193. def OpenDoor(self) -> bool:
  194. self.__logger.debug("Called OpenDoor")
  195. return self.__comm.OpenDoor(self.__playerID)
  196. def SkipWindow(self) -> bool:
  197. self.__logger.debug("Called SkipWindow")
  198. return self.__comm.SkipWindow(self.__playerID)
  199. def StartOpenGate(self) -> bool:
  200. self.__logger.debug("Called StartOpenGate")
  201. return self.__comm.StartOpenGate(self.__playerID)
  202. def StartOpenChest(self) -> bool:
  203. self.__logger.debug("Called StartOpenChest")
  204. return self.__comm.StartOpenChest(self.__playerID)
  205. def EndAllAction(self) -> bool:
  206. self.__logger.debug("Called EndAllAction")
  207. return self.__comm.EndAllAction(self.__playerID)
  208. def HaveView(self, gridX: int, gridY: int, selfX: int, selfY: int, viewRange: int) -> bool:
  209. with self.__mtxState:
  210. return AssistFunction.HaveView(viewRange, selfX, selfY, gridX, gridY, self.__currentState.gameMap)
  211. # Logic内部逻辑
  212. def __TryConnection(self) -> bool:
  213. self.__logger.info("Try to connect to server...")
  214. return self.__comm.TryConnection(self.__playerID)
  215. def __ProcessMessage(self) -> None:
  216. def messageThread():
  217. self.__logger.info("Message thread start!")
  218. self.__comm.AddPlayer(self.__playerID, self.__playerType)
  219. self.__logger.info("Join the player!")
  220. while self.__gameState != THUAI6.GameState.GameEnd:
  221. # 读取消息,无消息时此处阻塞
  222. clientMsg = self.__comm.GetMessage2Client()
  223. self.__logger.debug("Get message from server!")
  224. self.__gameState = Proto2THUAI6.gameStateDict[
  225. clientMsg.game_state]
  226. if self.__gameState == THUAI6.GameState.GameStart:
  227. # 读取玩家的GUID
  228. self.__logger.info("Game start!")
  229. for obj in clientMsg.obj_message:
  230. if obj.WhichOneof("message_of_obj") == "map_message":
  231. gameMap: List[List[THUAI6.PlaceType]] = []
  232. for row in obj.map_message.row:
  233. col: List[THUAI6.PlaceType] = []
  234. for place in row.col:
  235. col.append(
  236. Proto2THUAI6.placeTypeDict[place])
  237. gameMap.append(col)
  238. self.__currentState.gameMap = gameMap
  239. self.__bufferState.gameMap = gameMap
  240. self.__logger.info("Game map loaded!")
  241. break
  242. else:
  243. self.__logger.error("Map not found!")
  244. self.__LoadBuffer(clientMsg)
  245. self.__AILoop = True
  246. self.__UnBlockAI()
  247. elif self.__gameState == THUAI6.GameState.GameRunning:
  248. # 读取玩家的GUID
  249. self.__LoadBuffer(clientMsg)
  250. else:
  251. self.__logger.error("Unknown GameState!")
  252. continue
  253. with self.__cvBuffer:
  254. self.__bufferUpdated = True
  255. self.__counterBuffer = -1
  256. self.__cvBuffer.notify()
  257. self.__logger.info("Game End!")
  258. self.__logger.info("Message thread end!")
  259. self.__AILoop = False
  260. threading.Thread(target=messageThread).start()
  261. def __LoadBufferSelf(self, message: Message2Clients.MessageToClient) -> None:
  262. if self.__playerType == THUAI6.PlayerType.StudentPlayer:
  263. for item in message.obj_message:
  264. if item.WhichOneof("message_of_obj") == "student_message":
  265. if item.student_message.player_id == self.__playerID:
  266. self.__bufferState.self = Proto2THUAI6.Protobuf2THUAI6Student(
  267. item.student_message)
  268. self.__bufferState.students.append(
  269. self.__bufferState.self)
  270. else:
  271. self.__bufferState.students.append(
  272. Proto2THUAI6.Protobuf2THUAI6Student(item.student_message))
  273. self.__logger.debug("Add Student!")
  274. else:
  275. for item in message.obj_message:
  276. if item.WhichOneof("message_of_obj") == "tricker_message":
  277. if item.tricker_message.player_id == self.__playerID:
  278. self.__bufferState.self = Proto2THUAI6.Protobuf2THUAI6Tricker(
  279. item.tricker_message)
  280. self.__bufferState.trickers.append(
  281. self.__bufferState.self)
  282. else:
  283. self.__bufferState.trickers.append(
  284. Proto2THUAI6.Protobuf2THUAI6Tricker(item.tricker_message))
  285. self.__logger.debug("Add Tricker!")
  286. def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None:
  287. if self.__playerType == THUAI6.PlayerType.StudentPlayer and item.WhichOneof("message_of_obj") == "tricker_message":
  288. if MessageType.TRICKER_INVISIBLE in item.tricker_message.buff:
  289. return
  290. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.tricker_message.x, item.tricker_message.y, self.__bufferState.gameMap):
  291. self.__bufferState.trickers.append(
  292. Proto2THUAI6.Protobuf2THUAI6Tricker(item.tricker_message))
  293. self.__logger.debug("Add Tricker!")
  294. elif self.__playerType == THUAI6.PlayerType.TrickerPlayer and item.WhichOneof("message_of_obj") == "student_message":
  295. if THUAI6.TrickerBuffType.Clairaudience in self.__bufferState.self.buff:
  296. self.__bufferState.students.append(
  297. Proto2THUAI6.Protobuf2THUAI6Student(item.student_message))
  298. self.__logger.debug("Add Student!")
  299. return
  300. if MessageType.STUDENT_INVISIBLE in item.student_message.buff:
  301. return
  302. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.student_message.x, item.student_message.y, self.__bufferState.gameMap):
  303. self.__bufferState.students.append(
  304. Proto2THUAI6.Protobuf2THUAI6Student(item.student_message))
  305. self.__logger.debug("Add Student!")
  306. elif item.WhichOneof("message_of_obj") == "prop_message":
  307. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.prop_message.x, item.prop_message.y, self.__bufferState.gameMap):
  308. self.__bufferState.props.append(
  309. Proto2THUAI6.Protobuf2THUAI6Prop(item.prop_message))
  310. self.__logger.debug("Add Prop!")
  311. elif item.WhichOneof("message_of_obj") == "bullet_message":
  312. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.bullet_message.x, item.bullet_message.y, self.__bufferState.gameMap):
  313. self.__bufferState.bullets.append(
  314. Proto2THUAI6.Protobuf2THUAI6Bullet(item.bullet_message))
  315. self.__logger.debug("Add Bullet!")
  316. elif item.WhichOneof("message_of_obj") == "classroom_message":
  317. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.classroom_message.x, item.classroom_message.y, self.__bufferState.gameMap):
  318. pos = (AssistFunction.GridToCell(
  319. item.classroom_message.x), AssistFunction.GridToCell(item.classroom_message.y))
  320. if pos not in self.__bufferState.mapInfo.classroomState:
  321. self.__bufferState.mapInfo.classroomState[pos] = item.classroom_message.progress
  322. self.__logger.debug("Add Classroom!")
  323. else:
  324. self.__bufferState.mapInfo.classroomState[pos] = item.classroom_message.progress
  325. self.__logger.debug("Update Classroom!")
  326. elif item.WhichOneof("message_of_obj") == "chest_message":
  327. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.chest_message.x, item.chest_message.y, self.__bufferState.gameMap):
  328. pos = (AssistFunction.GridToCell(
  329. item.chest_message.x), AssistFunction.GridToCell(item.chest_message.y))
  330. if pos not in self.__bufferState.mapInfo.chestState:
  331. self.__bufferState.mapInfo.chestState[pos] = item.chest_message.progress
  332. self.__logger.debug(
  333. f"Add Chest at {pos[0]}, {pos[1]}")
  334. else:
  335. self.__bufferState.mapInfo.chestState[pos] = item.chest_message.progress
  336. self.__logger.debug(
  337. f"Update Chest at {pos[0]}, {pos[1]}")
  338. elif item.WhichOneof("message_of_obj") == "door_message":
  339. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.door_message.x, item.door_message.y, self.__bufferState.gameMap):
  340. pos = (AssistFunction.GridToCell(
  341. item.door_message.x), AssistFunction.GridToCell(item.door_message.y))
  342. if pos not in self.__bufferState.mapInfo.doorState:
  343. self.__bufferState.mapInfo.doorState[pos] = item.door_message.is_open
  344. self.__bufferState.mapInfo.doorProgress[pos] = item.door_message.progress
  345. self.__logger.debug("Add Door!")
  346. else:
  347. self.__bufferState.mapInfo.doorState[pos] = item.door_message.is_open
  348. self.__bufferState.mapInfo.doorProgress[pos] = item.door_message.progress
  349. self.__logger.debug("Update Door!")
  350. elif item.WhichOneof("message_of_obj") == "hidden_gate_message":
  351. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.hidden_gate_message.x, item.hidden_gate_message.y, self.__bufferState.gameMap):
  352. pos = (AssistFunction.GridToCell(
  353. item.hidden_gate_message.x), AssistFunction.GridToCell(item.hidden_gate_message.y))
  354. if pos not in self.__bufferState.mapInfo.hiddenGateState:
  355. self.__bufferState.mapInfo.hiddenGateState[pos] = Proto2THUAI6.Bool2HiddenGateState(
  356. item.hidden_gate_message.opened)
  357. self.__logger.debug("Add HiddenGate!")
  358. else:
  359. self.__bufferState.mapInfo.hiddenGateState[pos] = Proto2THUAI6.Bool2HiddenGateState(
  360. item.hidden_gate_message.opened)
  361. self.__logger.debug("Update HiddenGate!")
  362. elif item.WhichOneof("message_of_obj") == "gate_message":
  363. if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x, self.__bufferState.self.y, item.gate_message.x, item.gate_message.y, self.__bufferState.gameMap):
  364. pos = (AssistFunction.GridToCell(
  365. item.gate_message.x), AssistFunction.GridToCell(item.gate_message.y))
  366. if pos not in self.__bufferState.mapInfo.gateState:
  367. self.__bufferState.mapInfo.gateState[pos] = item.gate_message.progress
  368. self.__logger.debug("Add Gate!")
  369. else:
  370. self.__bufferState.mapInfo.gateState[pos] = item.gate_message.progress
  371. self.__logger.debug("Update Gate!")
  372. elif item.WhichOneof("message_of_obj") == "news_message":
  373. if item.news_message.to_id == self.__playerID:
  374. if item.news_message.WhichOneof("news") == "text_message":
  375. self.__messageQueue.put(
  376. (item.news_message.from_id, item.news_message.text_message))
  377. self.__logger.debug("Add News!")
  378. elif item.news_message.WhichOneof("news") == "binary_message":
  379. self.__messageQueue.put(
  380. (item.news_message.from_id, item.news_message.binary_message))
  381. self.__logger.debug("Add News!")
  382. else:
  383. self.__logger.error("Unknown News!")
  384. else:
  385. self.__logger.debug(
  386. "Unknown Message!")
  387. def __LoadBuffer(self, message: Message2Clients.MessageToClient) -> None:
  388. with self.__cvBuffer:
  389. self.__bufferState.students.clear()
  390. self.__bufferState.trickers.clear()
  391. self.__bufferState.props.clear()
  392. self.__bufferState.bullets.clear()
  393. self.__bufferState.bombedBullets.clear()
  394. self.__bufferState.guids.clear()
  395. self.__logger.debug("Buffer cleared!")
  396. for obj in message.obj_message:
  397. if obj.WhichOneof("message_of_obj") == "student_message":
  398. self.__bufferState.guids.append(obj.student_message.guid)
  399. for obj in message.obj_message:
  400. if obj.WhichOneof("message_of_obj") == "tricker_message":
  401. self.__bufferState.guids.append(obj.tricker_message.guid)
  402. self.__bufferState.gameInfo = Proto2THUAI6.Protobuf2THUAI6GameInfo(
  403. message.all_message)
  404. self.__LoadBufferSelf(message)
  405. for item in message.obj_message:
  406. self.__LoadBufferCase(item)
  407. if Setting.asynchronous():
  408. with self.__mtxState:
  409. self.__currentState, self.__bufferState = self.__bufferState, self.__currentState
  410. self.__counterState = self.__counterBuffer
  411. self.__logger.info("Update state!")
  412. self.__freshed = True
  413. else:
  414. self.__bufferUpdated = True
  415. self.__counterBuffer += 1
  416. self.__cvBuffer.notify()
  417. def __UnBlockAI(self) -> None:
  418. with self.__cvAI:
  419. self.__AIStart = True
  420. self.__cvAI.notify()
  421. def __Update(self) -> None:
  422. if not Setting.asynchronous():
  423. with self.__cvBuffer:
  424. self.__cvBuffer.wait_for(lambda: self.__bufferUpdated)
  425. with self.__mtxState:
  426. self.__bufferState, self.__currentState = self.__currentState, self.__bufferState
  427. self.__counterState = self.__counterBuffer
  428. self.__bufferUpdated = False
  429. self.__logger.info("Update state!")
  430. def __Wait(self) -> None:
  431. self.__freshed = False
  432. with self.__cvBuffer:
  433. self.__cvBuffer.wait_for(lambda: self.__freshed)
  434. def Main(self, createAI: Callable, IP: str, port: str, file: bool, screen: bool, warnOnly: bool) -> None:
  435. # 建立日志组件
  436. self.__logger.setLevel(logging.DEBUG)
  437. formatter = logging.Formatter(
  438. "[%(name)s] [%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s", '%H:%M:%S')
  439. # 确保文件存在
  440. # if not os.path.exists(os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + "/logs"):
  441. # os.makedirs(os.path.dirname(os.path.dirname(
  442. # os.path.realpath(__file__))) + "/logs")
  443. if platform.system().lower() == "windows":
  444. os.system(
  445. f"mkdir \"{os.path.dirname(os.path.dirname(os.path.realpath(__file__)))}\\logs\"")
  446. else:
  447. os.system(
  448. f"mkdir -p \"{os.path.dirname(os.path.dirname(os.path.realpath(__file__)))}/logs\"")
  449. fileHandler = logging.FileHandler(os.path.dirname(
  450. os.path.dirname(os.path.realpath(__file__))) + "/logs/logic" + str(self.__playerID) + "-log.txt", "w+", encoding="utf-8")
  451. screenHandler = logging.StreamHandler()
  452. if file:
  453. fileHandler.setLevel(logging.DEBUG)
  454. fileHandler.setFormatter(formatter)
  455. self.__logger.addHandler(fileHandler)
  456. if screen:
  457. if warnOnly:
  458. screenHandler.setLevel(logging.WARNING)
  459. else:
  460. screenHandler.setLevel(logging.INFO)
  461. screenHandler.setFormatter(formatter)
  462. self.__logger.addHandler(screenHandler)
  463. self.__logger.info("*********Basic Info*********")
  464. self.__logger.info("asynchronous: %s", Setting.asynchronous())
  465. self.__logger.info("server: %s:%s", IP, port)
  466. self.__logger.info("playerID: %s", self.__playerID)
  467. self.__logger.info("player type: %s", self.__playerType.name)
  468. self.__logger.info("****************************")
  469. # 建立通信组件
  470. self.__comm = Communication(IP, port)
  471. # 构造timer
  472. if self.__playerType == THUAI6.PlayerType.StudentPlayer:
  473. if not file and not screen:
  474. self.__timer = StudentAPI(self)
  475. else:
  476. self.__timer = StudentDebugAPI(
  477. self, file, screen, warnOnly, self.__playerID)
  478. elif self.__playerType == THUAI6.PlayerType.TrickerPlayer:
  479. if not file and not screen:
  480. self.__timer = TrickerAPI(self)
  481. else:
  482. self.__timer = TrickerDebugAPI(
  483. self, file, screen, warnOnly, self.__playerID)
  484. # 构建AI线程
  485. def AIThread():
  486. with self.__cvAI:
  487. self.__cvAI.wait_for(lambda: self.__AIStart)
  488. ai = createAI(self.__playerID)
  489. while self.__AILoop:
  490. if Setting.asynchronous():
  491. self.__Wait()
  492. self.__timer.StartTimer()
  493. self.__timer.Play(ai)
  494. self.__timer.EndTimer()
  495. else:
  496. self.__Update()
  497. self.__timer.StartTimer()
  498. self.__timer.Play(ai)
  499. self.__timer.EndTimer()
  500. if self.__TryConnection():
  501. self.__logger.info(
  502. "Connect to the server successfully, AI thread will be started.")
  503. self.__threadAI = threading.Thread(target=AIThread)
  504. self.__threadAI.start()
  505. self.__ProcessMessage()
  506. self.__logger.info("Join the AI thread.")
  507. self.__threadAI.join()
  508. else:
  509. self.__AILoop = False
  510. self.__logger.error("Failed to connect to the server.")
  511. return