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

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