mcp.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. from twisted.internet import reactor
  2. from twisted.internet import task
  3. from twisted.internet import defer
  4. from colorama import Fore, Back, Style
  5. from twisted.python import log
  6. class MCP(object):
  7. def __init__(self, game):
  8. self.game = game
  9. self.queue_game = None
  10. # we don't have this .. yet!
  11. self.prompt = None
  12. self.observer = None
  13. self.keepalive = None
  14. # Port Data
  15. self.portdata = None
  16. self.portcycle = None
  17. def finishSetup(self):
  18. # if self.queue_game is None:
  19. self.queue_game = self.game.queue_game
  20. # if self.observer is None:
  21. self.observer = self.game.observer
  22. self.observer.connect("hotkey", self.activate)
  23. self.observer.connect("notyet", self.notyet)
  24. self.observer.connect("close", self.close)
  25. def close(self, _):
  26. if self.keepalive:
  27. if self.keepalive.running:
  28. self.keepalive.stop()
  29. def notyet(self, _):
  30. """ No, not yet! """
  31. nl = "\n\r"
  32. r = Style.RESET_ALL
  33. log.msg("NNY!")
  34. prompt = self.game.buffer
  35. self.queue_game.put(
  36. r
  37. + nl
  38. + Style.BRIGHT
  39. + "Proxy:"
  40. + Style.RESET_ALL
  41. + " I can't activate at this time."
  42. + nl
  43. )
  44. self.queue_game.put(prompt)
  45. def stayAwake(self):
  46. """ Send a space to the game to keep it alive/don't timeout. """
  47. log.msg("Gameserver, stay awake.")
  48. self.game.queue_player.put(" ")
  49. def startAwake(self):
  50. """ Start the task that keeps the game server alive.
  51. There is currently a bug in there somewhere, which causes it to
  52. duplicate:
  53. 2019-11-25 21:19:03-0500 [-] Gameserver, stay awake.
  54. 2019-11-25 21:19:14-0500 [-] Gameserver, stay awake.
  55. 2019-11-25 21:19:24-0500 [-] Gameserver, stay awake.
  56. 2019-11-25 21:19:27-0500 [-] Gameserver, stay awake.
  57. 2019-11-25 21:19:31-0500 [-] Gameserver, stay awake.
  58. 2019-11-25 21:19:33-0500 [-] Gameserver, stay awake.
  59. 2019-11-25 21:19:44-0500 [-] Gameserver, stay awake.
  60. 2019-11-25 21:19:54-0500 [-] Gameserver, stay awake.
  61. 2019-11-25 21:19:57-0500 [-] Gameserver, stay awake.
  62. 2019-11-25 21:20:01-0500 [-] Gameserver, stay awake.
  63. 2019-11-25 21:20:03-0500 [-] Gameserver, stay awake.
  64. ^ These aren't 30 seconds apart.
  65. These are being sent, even when the MCP is not active!
  66. """
  67. self.keepalive = task.LoopingCall(self.stayAwake)
  68. self.keepalive.start(30)
  69. def activate(self, _):
  70. log.msg("MCP menu called.")
  71. # We want the raw one, not the ANSI cleaned getPrompt.
  72. prompt = self.game.buffer
  73. if not self.prompt is None:
  74. # silly, we're already active
  75. log.msg("I think we're already active. Ignoring request.")
  76. return
  77. # Or will the caller setup/restore the prompt?
  78. self.prompt = prompt
  79. # queue_game = to player
  80. self.displayMenu()
  81. self.observer.connect("player", self.fromPlayer)
  82. # TODO: Add background "keepalive" event so the game doesn't time out on us.
  83. self.startAwake()
  84. # self.keepalive = task.LoopingCall(self.stayAwake)
  85. # self.keepalive.start(30)
  86. def displayMenu(self):
  87. nl = "\n\r"
  88. c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  89. r = Style.RESET_ALL
  90. c1 = merge(Style.BRIGHT + Fore.BLUE)
  91. c2 = merge(Style.NORMAL + Fore.BLUE)
  92. self.queue_game.put(nl + c + "TradeWars Proxy active." + r + nl)
  93. self.queue_game.put(" " + c1 + "D" + c2 + " - " + c1 + "Diagnostics" + nl)
  94. self.queue_game.put(
  95. " " + c1 + "T" + c2 + " - " + c1 + "Display current Time" + nl
  96. )
  97. self.queue_game.put(" " + c1 + "P" + c2 + " - " + c1 + "Port CIM Report" + nl)
  98. self.queue_game.put(" " + c1 + "S" + c2 + " - " + c1 + "Scripts" + nl)
  99. self.queue_game.put(" " + c1 + "X" + c2 + " - " + c1 + "eXit" + nl)
  100. self.queue_game.put(" " + c + "-=>" + r + " ")
  101. def fromPlayer(self, chunk):
  102. """ Data from player (in bytes). """
  103. chunk = chunk.decode("utf-8", "ignore")
  104. nl = "\n\r"
  105. c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  106. r = Style.RESET_ALL
  107. c1 = merge(Style.BRIGHT + Fore.BLUE)
  108. c2 = merge(Style.NORMAL + Fore.BLUE)
  109. key = chunk.upper()
  110. if key == "T":
  111. self.queue_game.put(c + key + r + nl)
  112. now = pendulum.now()
  113. log.msg("Time")
  114. self.queue_game.put(
  115. nl + c1 + "It is currently " + now.to_datetime_string() + "." + nl
  116. )
  117. self.displayMenu()
  118. elif key == "P":
  119. log.msg("Port")
  120. self.queue_game.put(c + key + r + nl)
  121. self.portReport()
  122. # self.queue_game.put(nl + c + "NO, NOT YET!" + r + nl)
  123. # self.displayMenu()
  124. elif key == "S":
  125. log.msg("Scripts")
  126. self.queue_game.put(c + key + r + nl)
  127. self.scripts()
  128. elif key == "D":
  129. self.queue_game.put(nl + "Diagnostics" + nl + "portdata:" + nl)
  130. line = pformat(self.portdata).replace("\n", "\n\r")
  131. self.queue_game.put(line + nl)
  132. self.displayMenu()
  133. elif key == "X":
  134. log.msg('"Quit, return to "normal". (Whatever that means!)')
  135. self.queue_game.put(c + key + r + nl)
  136. self.observer.disconnect("player", self.fromPlayer)
  137. self.queue_game.put(nl + c1 + "Returning to game" + c2 + "..." + r + nl)
  138. self.queue_game.put(self.prompt)
  139. self.prompt = None
  140. self.keepalive.stop()
  141. self.keepalive = None
  142. self.game.to_player = True
  143. else:
  144. if key.isprintable():
  145. self.queue_game.put(r + nl)
  146. self.queue_game.put("Excuse me? I don't understand '" + key + "'." + nl)
  147. self.displayMenu()
  148. def portReport(self):
  149. """ Activate CIM and request Port Report """
  150. self.game.to_player = False
  151. self.portdata = None
  152. self.observer.connect("prompt", self.portPrompt)
  153. self.observer.connect("game-line", self.portParse)
  154. self.game.queue_player.put("^")
  155. def portPrompt(self, prompt):
  156. if prompt == ": ":
  157. log.msg("CIM Prompt")
  158. if self.portdata is None:
  159. log.msg("R - Port Report")
  160. self.portdata = dict()
  161. self.game.queue_player.put("R")
  162. self.portcycle = cycle(["/", "-", "\\", "|"])
  163. self.queue_game.put(" ")
  164. else:
  165. log.msg("Q - Quit")
  166. self.game.queue_player.put("Q")
  167. self.portcycle = None
  168. def portBS(self, info):
  169. if info[0] == "-":
  170. bs = "B"
  171. else:
  172. bs = "S"
  173. return (bs, int(info[1:].strip()))
  174. def portParse(self, line):
  175. if line == "":
  176. return
  177. if line == ": ":
  178. return
  179. log.msg("parse line:", line)
  180. if line.startswith("Command [TL="):
  181. return
  182. if line == ": ENDINTERROG":
  183. log.msg("CIM Done")
  184. log.msg(pformat(self.portdata))
  185. self.queue_game.put("\b \b" + "\n\r")
  186. self.observer.disconnect("prompt", self.portPrompt)
  187. self.observer.disconnect("game-line", self.portParse)
  188. self.game.to_player = True
  189. # self.keepalive.start(30)
  190. self.startAwake()
  191. self.displayMenu()
  192. return
  193. # Give some sort of feedback to the user.
  194. if self.portcycle:
  195. if len(self.portdata) % 10 == 0:
  196. self.queue_game.put("\b" + next(self.portcycle))
  197. # Ok, we need to parse this line
  198. # 436 2870 100% - 1520 100% - 2820 100%
  199. # 2 1950 100% - 1050 100% 2780 100%
  200. # 5 2800 100% - 2330 100% - 1230 100%
  201. # 8 2890 100% 1530 100% - 2310 100%
  202. # 9 - 2160 100% 2730 100% - 2120 100%
  203. # 324 - 2800 100% 2650 100% - 2490 100%
  204. # 492 990 100% 900 100% 1660 100%
  205. # 890 1920 100% - 2140 100% 1480 100%
  206. # 1229 - 2870 100% - 1266 90% 728 68%
  207. # 1643 - 3000 100% - 3000 100% - 3000 100%
  208. # 1683 - 1021 97% 1460 100% - 2620 100%
  209. # 1898 - 1600 100% - 1940 100% - 1860 100%
  210. # 2186 1220 100% - 900 100% - 1840 100%
  211. # 2194 2030 100% - 1460 100% - 1080 100%
  212. # 2577 2810 100% - 1550 100% - 2350 100%
  213. # 2629 2570 100% - 2270 100% - 1430 100%
  214. # 3659 - 1720 100% 1240 100% - 2760 100%
  215. # 3978 - 920 100% 2560 100% - 2590 100%
  216. # 4302 348 25% - 2530 100% - 316 23%
  217. # 4516 - 1231 60% - 1839 75% 7 0%
  218. work = line.replace("%", "")
  219. parts = re.split(r"(?<=\d)\s", work)
  220. if len(parts) == 8:
  221. port = int(parts[0].strip())
  222. data = dict()
  223. data["fuel"] = dict()
  224. data["fuel"]["sale"], data["fuel"]["units"] = self.portBS(parts[1])
  225. data["fuel"]["pct"] = int(parts[2].strip())
  226. data["org"] = dict()
  227. data["org"]["sale"], data["org"]["units"] = self.portBS(parts[3])
  228. data["org"]["pct"] = int(parts[4].strip())
  229. data["equ"] = dict()
  230. data["equ"]["sale"], data["equ"]["units"] = self.portBS(parts[5])
  231. data["equ"]["pct"] = int(parts[6].strip())
  232. # Store what this port is buying/selling
  233. data["port"] = (
  234. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  235. )
  236. # Convert BBS/SBB to Class number 1-8
  237. data["class"] = CLASSES_PORT[data["port"]]
  238. self.portdata[port] = data
  239. else:
  240. self.queue_game.put("?")
  241. log.msg("Line in question is: [{0}].".format(line))
  242. log.msg(repr(parts))
  243. def scripts(self):
  244. self.script = dict()
  245. self.observer.disconnect("player", self.fromPlayer)
  246. self.observer.connect("player", self.scriptFromPlayer)
  247. self.observer.connect("game-line", self.scriptLine)
  248. nl = "\n\r"
  249. c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  250. r = Style.RESET_ALL
  251. c1 = merge(Style.BRIGHT + Fore.CYAN)
  252. c2 = merge(Style.NORMAL + Fore.CYAN)
  253. self.queue_game.put(nl + c + "TradeWars Proxy Script(s)" + r + nl)
  254. self.queue_game.put(" " + c1 + "P" + c2 + " - " + c1 + "Port Trading Pair" + nl)
  255. self.queue_game.put(" " + c + "-=>" + r + " ")
  256. def unscript(self):
  257. self.observer.connect("player", self.fromPlayer)
  258. self.observer.disconnect("player", self.scriptFromPlayer)
  259. self.observer.disconnect("game-line", self.scriptLine)
  260. self.displayMenu()
  261. def scriptLine(self, line):
  262. pass
  263. def scriptFromPlayer(self, chunk):
  264. """ Data from player (in bytes). """
  265. chunk = chunk.decode("utf-8", "ignore")
  266. nl = "\n\r"
  267. c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  268. r = Style.RESET_ALL
  269. key = chunk.upper()
  270. if key == "Q":
  271. self.queue_game.put(c + key + r + nl)
  272. self.observer.connect("player", self.fromPlayer)
  273. self.observer.disconnect("player", self.scriptFromPlayer)
  274. self.observer.disconnect("game-line", self.scriptLine)
  275. self.observer.connect("game-line", self.portParse)
  276. self.displayMenu()
  277. elif key == "P":
  278. self.queue_game.put(c + key + r + nl)
  279. d = self.playerInput("Enter sector to trade to: ", 6)
  280. d.addCallback(self.save_sector)
  281. def save_sector(self, sector):
  282. log.msg("save_sector {0}".format(sector))
  283. if sector.strip() == "":
  284. self.queue_game.put("Script Aborted.")
  285. self.unscript()
  286. return
  287. s = int(sector.strip())
  288. self.script["sector"] = s
  289. d = self.playerInput("Enter times to execute script: ", 6)
  290. d.addCallback(self.save_loop)
  291. def save_loop(self, loop):
  292. log.msg("save_loop {0}".format(loop))
  293. if loop.strip() == "":
  294. self.queue_game.put("Script Aborted.")
  295. self.unscript()
  296. return
  297. l = int(loop.strip())
  298. self.script["loop"] = l
  299. d = self.playerInput("Enter markup/markdown percentage: ", 3)
  300. d.addCallback(self.save_mark)
  301. def save_mark(self, mark):
  302. log.msg("save_mark {0}".format(mark))
  303. if mark.strip() == "":
  304. self.script["mark"] = 5
  305. else:
  306. self.script["mark"] = int(mark.strip())
  307. # Ok, we have the values we need to run the Port trade script
  308. self.queue_game.put(pformat(self.script).replace("\n", "\n\r"))
  309. self.unscript()
  310. def playerInput(self, prompt, limit):
  311. """ Given a prompt and limit, this handles user input.
  312. This displays the prompt, and sets up the proper
  313. observers, while preserving the "current" ones.
  314. This returns a deferred, so you can chain the results
  315. of this.
  316. """
  317. log.msg("playerInput({0}, {1}".format(prompt, limit))
  318. nl = "\n\r"
  319. c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  320. r = Style.RESET_ALL
  321. self.queue_game.put(r + nl + c + prompt)
  322. # This should set the background and show the size of the entry area.
  323. self.queue_game.put(" " * limit + "\b" * limit)
  324. d = defer.Deferred()
  325. self.player_input = d
  326. self.input_limit = limit
  327. self.input_input = ""
  328. self.save = self.observer.save()
  329. self.observer.connect("player", self.niceInput)
  330. # input_funcs = { 'player': [self.niceInput] }
  331. # self.observer.set_funcs(input_funcs)
  332. return d
  333. def niceInput(self, chunk):
  334. """ Data from player (in bytes). """
  335. chunk = chunk.decode("utf-8", "ignore")
  336. # log.msg("niceInput:", repr(chunk))
  337. r = Style.RESET_ALL
  338. for c in chunk:
  339. if c == "\b":
  340. # Backspace
  341. if len(self.input_input) > 0:
  342. self.queue_game.put("\b \b")
  343. self.input_input = self.input_input[0:-1]
  344. else:
  345. # Can't
  346. self.queue_game.put("\a")
  347. if c == "\r":
  348. # Ok, completed!
  349. self.queue_game.put(r + "\n\r")
  350. self.observer.load(self.save)
  351. self.save = None
  352. line = self.input_input
  353. log.msg("finishing niceInput {0}".format(line))
  354. # self.queue_game.put("[{0}]\n\r".format(line))
  355. self.input_input = ""
  356. # Ok, maybe this isn't the way to do this ...
  357. # self.player_input.callback(line)
  358. reactor.callLater(0, self.player_input.callback, line)
  359. self.player_input = None
  360. if c.isprintable():
  361. if len(self.input_input) + 1 <= self.input_limit:
  362. self.input_input += c
  363. self.queue_game.put(c)
  364. else:
  365. # Limit reached
  366. self.queue_game.put("\a")