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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. import os
  2. from typing import List, Union, Callable, Tuple
  3. import threading
  4. import logging
  5. import copy
  6. import proto.MessageType_pb2 as MessageType
  7. import proto.Message2Server_pb2 as Message2Server
  8. import proto.Message2Clients_pb2 as Message2Clients
  9. from queue import Queue
  10. import PyAPI.structures as THUAI6
  11. from PyAPI.utils import Proto2THUAI6, AssistFunction
  12. from PyAPI.DebugAPI import StudentDebugAPI, TrickerDebugAPI
  13. from PyAPI.API import StudentAPI, TrickerAPI
  14. from PyAPI.AI import Setting
  15. from PyAPI.Communication import Communication
  16. from PyAPI.State import State
  17. from PyAPI.Interface import ILogic, IGameTimer
  18. class Logic(ILogic):
  19. def __init__(self, playerID: int, playerType: THUAI6.PlayerType) -> None:
  20. # ID
  21. self.__playerID: int = playerID
  22. self.__playerGUIDs: List[int] = []
  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: str) -> 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, str]:
  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.__playerGUIDs)
  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. # Logic内部逻辑
  209. def __TryConnection(self) -> bool:
  210. self.__logger.info("Try to connect to server...")
  211. return self.__comm.TryConnection(self.__playerID)
  212. def __ProcessMessage(self) -> None:
  213. def messageThread():
  214. self.__logger.info("Message thread start!")
  215. self.__comm.AddPlayer(self.__playerID, self.__playerType)
  216. self.__logger.info("Join the player!")
  217. while self.__gameState != THUAI6.GameState.GameEnd:
  218. # 读取消息,无消息时此处阻塞
  219. clientMsg = self.__comm.GetMessage2Client()
  220. self.__logger.debug("Get message from server!")
  221. self.__gameState = Proto2THUAI6.gameStateDict[
  222. clientMsg.game_state]
  223. if self.__gameState == THUAI6.GameState.GameStart:
  224. # 读取玩家的GUID
  225. self.__logger.info("Game start!")
  226. self.__playerGUIDs.clear()
  227. for obj in clientMsg.obj_message:
  228. if obj.WhichOneof("message_of_obj") == "student_message":
  229. self.__playerGUIDs.append(obj.student_message.guid)
  230. for obj in clientMsg.obj_message:
  231. if obj.WhichOneof("message_of_obj") == "tricker_message":
  232. self.__playerGUIDs.append(obj.tricker_message.guid)
  233. self.__currentState.guids = self.__playerGUIDs
  234. self.__bufferState.guids = self.__playerGUIDs
  235. for obj in clientMsg.obj_message:
  236. if obj.WhichOneof("message_of_obj") == "map_message":
  237. gameMap: List[List[THUAI6.PlaceType]] = []
  238. for row in obj.map_message.row:
  239. col: List[THUAI6.PlaceType] = []
  240. for place in row.col:
  241. col.append(
  242. Proto2THUAI6.placeTypeDict[place])
  243. gameMap.append(col)
  244. self.__currentState.gameMap = gameMap
  245. self.__bufferState.gameMap = gameMap
  246. self.__logger.info("Game map loaded!")
  247. break
  248. else:
  249. self.__logger.error("Map not found!")
  250. self.__LoadBuffer(clientMsg)
  251. self.__AILoop = True
  252. self.__UnBlockAI()
  253. elif self.__gameState == THUAI6.GameState.GameRunning:
  254. # 读取玩家的GUID
  255. self.__playerGUIDs.clear()
  256. for obj in clientMsg.obj_message:
  257. if obj.WhichOneof("message_of_obj") == "student_message":
  258. self.__playerGUIDs.append(obj.student_message.guid)
  259. for obj in clientMsg.obj_message:
  260. if obj.WhichOneof("message_of_obj") == "tricker_message":
  261. self.__playerGUIDs.append(obj.tricker_message.guid)
  262. self.__currentState.guids = self.__playerGUIDs
  263. self.__bufferState.guids = self.__playerGUIDs
  264. self.__LoadBuffer(clientMsg)
  265. else:
  266. self.__logger.error("Unknown GameState!")
  267. continue
  268. self.__AILoop = False
  269. with self.__cvBuffer:
  270. self.__bufferUpdated = True
  271. self.__counterBuffer = -1
  272. self.__cvBuffer.notify()
  273. self.__logger.info("Game End!")
  274. self.__logger.info("Message thread end!")
  275. threading.Thread(target=messageThread).start()
  276. def __LoadBuffer(self, message: Message2Clients.MessageToClient) -> None:
  277. with self.__cvBuffer:
  278. self.__bufferState.students.clear()
  279. self.__bufferState.trickers.clear()
  280. self.__bufferState.props.clear()
  281. self.__logger.debug("Buffer cleared!")
  282. self.__bufferState.gameInfo = Proto2THUAI6.Protobuf2THUAI6GameInfo(
  283. message.all_message)
  284. if self.__playerType == THUAI6.PlayerType.StudentPlayer:
  285. for item in message.obj_message:
  286. if item.WhichOneof("message_of_obj") == "student_message":
  287. if item.student_message.player_id == self.__playerID:
  288. self.__bufferState.self = Proto2THUAI6.Protobuf2THUAI6Student(
  289. item.student_message)
  290. self.__bufferState.students.append(
  291. self.__bufferState.self)
  292. else:
  293. self.__bufferState.students.append(
  294. Proto2THUAI6.Protobuf2THUAI6Student(item.student_message))
  295. self.__logger.debug("Add Student!")
  296. for item in message.obj_message:
  297. if item.WhichOneof("message_of_obj") == "tricker_message":
  298. if MessageType.TRICKER_INVISIBLE in item.tricker_message.buff:
  299. continue
  300. 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):
  301. self.__bufferState.trickers.append(
  302. Proto2THUAI6.Protobuf2THUAI6Tricker(item.tricker_message))
  303. self.__logger.debug("Add Tricker!")
  304. elif item.WhichOneof("message_of_obj") == "prop_message":
  305. 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):
  306. self.__bufferState.props.append(
  307. Proto2THUAI6.Protobuf2THUAI6Prop(item.prop_message))
  308. self.__logger.debug("Add Prop!")
  309. elif item.WhichOneof("message_of_obj") == "bullet_message":
  310. 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):
  311. self.__bufferState.bullets.append(
  312. Proto2THUAI6.Protobuf2THUAI6Bullet(item.bullet_message))
  313. self.__logger.debug("Add Bullet!")
  314. elif item.WhichOneof("message_of_obj") == "classroom_message":
  315. 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):
  316. pos = (AssistFunction.GridToCell(
  317. item.classroom_message.x), AssistFunction.GridToCell(item.classroom_message.y))
  318. if pos not in self.__bufferState.mapInfo.classroomState:
  319. self.__bufferState.mapInfo.classroomState[pos] = item.classroom_message.progress
  320. self.__logger.debug("Add Classroom!")
  321. else:
  322. self.__bufferState.mapInfo.classroomState[pos] = item.classroom_message.progress
  323. self.__logger.debug("Update Classroom!")
  324. elif item.WhichOneof("message_of_obj") == "chest_message":
  325. 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):
  326. pos = (AssistFunction.GridToCell(
  327. item.chest_message.x), AssistFunction.GridToCell(item.chest_message.y))
  328. if pos not in self.__bufferState.mapInfo.chestState:
  329. self.__bufferState.mapInfo.chestState[pos] = item.chest_message.progress
  330. self.__logger.debug(
  331. f"Add Chest at {pos[0]}, {pos[1]}")
  332. else:
  333. self.__bufferState.mapInfo.chestState[pos] = item.chest_message.progress
  334. self.__logger.debug(
  335. f"Update Chest at {pos[0]}, {pos[1]}")
  336. elif item.WhichOneof("message_of_obj") == "door_message":
  337. 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):
  338. pos = (AssistFunction.GridToCell(
  339. item.door_message.x), AssistFunction.GridToCell(item.door_message.y))
  340. if pos not in self.__bufferState.mapInfo.doorState:
  341. self.__bufferState.mapInfo.doorState[pos] = item.door_message.is_open
  342. self.__bufferState.mapInfo.doorProgress[pos] = item.door_message.progress
  343. self.__logger.debug("Add Door!")
  344. else:
  345. self.__bufferState.mapInfo.doorState[pos] = item.door_message.is_open
  346. self.__bufferState.mapInfo.doorProgress[pos] = item.door_message.progress
  347. self.__logger.debug("Update Door!")
  348. elif item.WhichOneof("message_of_obj") == "hidden_gate_message":
  349. 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):
  350. pos = (AssistFunction.GridToCell(
  351. item.hidden_gate_message.x), AssistFunction.GridToCell(item.hidden_gate_message.y))
  352. if pos not in self.__bufferState.mapInfo.hiddenGateState:
  353. self.__bufferState.mapInfo.hiddenGateState[pos] = Proto2THUAI6.Bool2HiddenGateState(
  354. item.hidden_gate_message.opened)
  355. self.__logger.debug("Add HiddenGate!")
  356. else:
  357. self.__bufferState.mapInfo.hiddenGateState[pos] = Proto2THUAI6.Bool2HiddenGateState(
  358. item.hidden_gate_message.opened)
  359. self.__logger.debug("Update HiddenGate!")
  360. elif item.WhichOneof("message_of_obj") == "gate_message":
  361. 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):
  362. pos = (AssistFunction.GridToCell(
  363. item.gate_message.x), AssistFunction.GridToCell(item.gate_message.y))
  364. if pos not in self.__bufferState.mapInfo.gateState:
  365. self.__bufferState.mapInfo.gateState[pos] = item.gate_message.progress
  366. self.__logger.debug("Add Gate!")
  367. else:
  368. self.__bufferState.mapInfo.gateState[pos] = item.gate_message.progress
  369. self.__logger.debug("Update Gate!")
  370. elif item.WhichOneof("message_of_obj") == "news_message":
  371. if item.news_message.to_id == self.__playerID:
  372. self.__messageQueue.put(
  373. (item.news_message.from_id, item.news_message.news))
  374. self.__logger.debug("Add News!")
  375. else:
  376. self.__logger.debug(
  377. "Unknown Message!")
  378. else:
  379. for item in message.obj_message:
  380. if item.WhichOneof("message_of_obj") == "tricker_message":
  381. if item.tricker_message.player_id == self.__playerID:
  382. self.__bufferState.self = Proto2THUAI6.Protobuf2THUAI6Tricker(
  383. item.tricker_message)
  384. self.__bufferState.trickers.append(
  385. self.__bufferState.self)
  386. else:
  387. self.__bufferState.trickers.append(
  388. Proto2THUAI6.Protobuf2THUAI6Tricker(item.tricker_message))
  389. self.__logger.debug("Add Tricker!")
  390. for item in message.obj_message:
  391. if item.WhichOneof("message_of_obj") == "student_message":
  392. if THUAI6.TrickerBuffType.Clairaudience in self.__bufferState.self.buff:
  393. self.__bufferState.students.append(
  394. Proto2THUAI6.Protobuf2THUAI6Student(item.student_message))
  395. self.__logger.debug("Add Student!")
  396. continue
  397. if MessageType.STUDENT_INVISIBLE in item.student_message.buff:
  398. continue
  399. 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):
  400. self.__bufferState.students.append(
  401. Proto2THUAI6.Protobuf2THUAI6Student(item.student_message))
  402. self.__logger.debug("Add Student!")
  403. elif item.WhichOneof("message_of_obj") == "prop_message":
  404. 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):
  405. self.__bufferState.props.append(
  406. Proto2THUAI6.Protobuf2THUAI6Prop(item.prop_message))
  407. self.__logger.debug("Add Prop!")
  408. elif item.WhichOneof("message_of_obj") == "bullet_message":
  409. 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):
  410. self.__bufferState.bullets.append(
  411. Proto2THUAI6.Protobuf2THUAI6Bullet(item.bullet_message))
  412. self.__logger.debug("Add Bullet!")
  413. elif item.WhichOneof("message_of_obj") == "classroom_message":
  414. 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):
  415. pos = (AssistFunction.GridToCell(
  416. item.classroom_message.x), AssistFunction.GridToCell(item.classroom_message.y))
  417. if pos not in self.__bufferState.mapInfo.classroomState:
  418. self.__bufferState.mapInfo.classroomState[pos] = item.classroom_message.progress
  419. self.__logger.debug("Add Classroom!")
  420. else:
  421. self.__bufferState.mapInfo.classroomState[pos] = item.classroom_message.progress
  422. self.__logger.debug("Update Classroom!")
  423. elif item.WhichOneof("message_of_obj") == "chest_message":
  424. 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):
  425. pos = (AssistFunction.GridToCell(
  426. item.chest_message.x), AssistFunction.GridToCell(item.chest_message.y))
  427. if pos not in self.__bufferState.mapInfo.chestState:
  428. self.__bufferState.mapInfo.chestState[pos] = item.chest_message.progress
  429. self.__logger.debug(
  430. f"Add Chest at {pos[0]}, {pos[1]}")
  431. else:
  432. self.__bufferState.mapInfo.chestState[pos] = item.chest_message.progress
  433. self.__logger.debug(
  434. f"Update Chest at {pos[0]}, {pos[1]}")
  435. elif item.WhichOneof("message_of_obj") == "door_message":
  436. 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):
  437. pos = (AssistFunction.GridToCell(
  438. item.door_message.x), AssistFunction.GridToCell(item.door_message.y))
  439. if pos not in self.__bufferState.mapInfo.doorState:
  440. self.__bufferState.mapInfo.doorState[pos] = item.door_message.is_open
  441. self.__bufferState.mapInfo.doorProgress[pos] = item.door_message.progress
  442. self.__logger.debug("Add Door!")
  443. else:
  444. self.__bufferState.mapInfo.doorState[pos] = item.door_message.is_open
  445. self.__bufferState.mapInfo.doorProgress[pos] = item.door_message.progress
  446. self.__logger.debug("Update Door!")
  447. elif item.WhichOneof("message_of_obj") == "hidden_gate_message":
  448. 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):
  449. pos = (AssistFunction.GridToCell(
  450. item.hidden_gate_message.x), AssistFunction.GridToCell(item.hidden_gate_message.y))
  451. if pos not in self.__bufferState.mapInfo.hiddenGateState:
  452. self.__bufferState.mapInfo.hiddenGateState[pos] = Proto2THUAI6.Bool2HiddenGateState(
  453. item.hidden_gate_message.opened)
  454. self.__logger.debug("Add HiddenGate!")
  455. else:
  456. self.__bufferState.mapInfo.hiddenGateState[pos] = Proto2THUAI6.Bool2HiddenGateState(
  457. item.hidden_gate_message.opened)
  458. self.__logger.debug("Update HiddenGate!")
  459. elif item.WhichOneof("message_of_obj") == "gate_message":
  460. 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):
  461. pos = (AssistFunction.GridToCell(
  462. item.gate_message.x), AssistFunction.GridToCell(item.gate_message.y))
  463. if pos not in self.__bufferState.mapInfo.gateState:
  464. self.__bufferState.mapInfo.gateState[pos] = item.gate_message.progress
  465. self.__logger.debug("Add Gate!")
  466. else:
  467. self.__bufferState.mapInfo.gateState[pos] = item.gate_message.progress
  468. self.__logger.debug("Update Gate!")
  469. else:
  470. self.__logger.debug("Unknown Message!")
  471. if Setting.asynchronous():
  472. with self.__mtxState:
  473. self.__currentState, self.__bufferState = self.__bufferState, self.__currentState
  474. self.__logger.info("Update state!")
  475. self.__freshed = True
  476. else:
  477. self.__bufferUpdated = True
  478. self.__counterBuffer += 1
  479. self.__cvBuffer.notify()
  480. def __UnBlockAI(self) -> None:
  481. with self.__cvAI:
  482. self.__AIStart = True
  483. self.__cvAI.notify()
  484. def __Update(self) -> None:
  485. if not Setting.asynchronous():
  486. with self.__cvBuffer:
  487. self.__cvBuffer.wait_for(lambda: self.__bufferUpdated)
  488. with self.__mtxState:
  489. self.__bufferState, self.__currentState = self.__currentState, self.__bufferState
  490. self.__counterState = self.__counterBuffer
  491. self.__bufferUpdated = False
  492. self.__logger.info("Update state!")
  493. def __Wait(self) -> None:
  494. self.__freshed = False
  495. with self.__cvBuffer:
  496. self.__cvBuffer.wait_for(lambda: self.__freshed)
  497. def Main(self, createAI: Callable, IP: str, port: str, file: bool, screen: bool, warnOnly: bool) -> None:
  498. # 建立日志组件
  499. self.__logger.setLevel(logging.DEBUG)
  500. formatter = logging.Formatter(
  501. "[%(name)s] [%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s", '%H:%M:%S')
  502. # 确保文件存在
  503. if not os.path.exists(os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + "/logs"):
  504. os.makedirs(os.path.dirname(os.path.dirname(
  505. os.path.realpath(__file__))) + "/logs")
  506. fileHandler = logging.FileHandler(os.path.dirname(
  507. os.path.dirname(os.path.realpath(__file__))) + "/logs/logic" + str(self.__playerID) + "-log.txt", "w+", encoding="utf-8")
  508. screenHandler = logging.StreamHandler()
  509. if file:
  510. fileHandler.setLevel(logging.DEBUG)
  511. fileHandler.setFormatter(formatter)
  512. self.__logger.addHandler(fileHandler)
  513. if screen:
  514. if warnOnly:
  515. screenHandler.setLevel(logging.WARNING)
  516. else:
  517. screenHandler.setLevel(logging.INFO)
  518. screenHandler.setFormatter(formatter)
  519. self.__logger.addHandler(screenHandler)
  520. self.__logger.info("*********Basic Info*********")
  521. self.__logger.info("asynchronous: %s", Setting.asynchronous())
  522. self.__logger.info("server: %s:%s", IP, port)
  523. self.__logger.info("playerID: %s", self.__playerID)
  524. self.__logger.info("player type: %s", self.__playerType.name)
  525. self.__logger.info("****************************")
  526. # 建立通信组件
  527. self.__comm = Communication(IP, port)
  528. # 构造timer
  529. if self.__playerType == THUAI6.PlayerType.StudentPlayer:
  530. if not file and not screen:
  531. self.__timer = StudentAPI(self)
  532. else:
  533. self.__timer = StudentDebugAPI(
  534. self, file, screen, warnOnly, self.__playerID)
  535. elif self.__playerType == THUAI6.PlayerType.TrickerPlayer:
  536. if not file and not screen:
  537. self.__timer = TrickerAPI(self)
  538. else:
  539. self.__timer = TrickerDebugAPI(
  540. self, file, screen, warnOnly, self.__playerID)
  541. # 构建AI线程
  542. def AIThread():
  543. with self.__cvAI:
  544. self.__cvAI.wait_for(lambda: self.__AIStart)
  545. ai = createAI(self.__playerID)
  546. while self.__AILoop:
  547. if Setting.asynchronous():
  548. self.__Wait()
  549. self.__timer.StartTimer()
  550. self.__timer.Play(ai)
  551. self.__timer.EndTimer()
  552. else:
  553. self.__Update()
  554. self.__timer.StartTimer()
  555. self.__timer.Play(ai)
  556. self.__timer.EndTimer()
  557. if self.__TryConnection():
  558. self.__logger.info(
  559. "Connect to the server successfully, AI thread will be started.")
  560. self.__threadAI = threading.Thread(target=AIThread)
  561. self.__threadAI.start()
  562. self.__ProcessMessage()
  563. self.__logger.info("Join the AI thread.")
  564. self.__threadAI.join()
  565. else:
  566. self.__AILoop = False
  567. self.__logger.error("Failed to connect to the server.")
  568. return