flexible.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. from twisted.internet.task import coiterate
  7. from twisted.internet.defer import gatherResults
  8. from itertools import cycle
  9. import pendulum
  10. from pprint import pformat
  11. from galaxy import GameData, PORT_CLASSES, CLASSES_PORT
  12. class SpinningCursor(object):
  13. """ Spinner class, that handles every so many clicks
  14. s = SpinningCursor(5) # every 5
  15. for x in range(10):
  16. if s.click():
  17. print(s.cycle())
  18. """
  19. def __init__(self, every=10):
  20. self.itercycle = cycle(["/", "-", "\\", "|"])
  21. self.count = 0
  22. self.every = every
  23. def reset(self):
  24. self.itercycle = cycle(["/", "-", "\\", "|"])
  25. self.count = 0
  26. def click(self):
  27. self.count += 1
  28. return self.count % self.every == 0
  29. def cycle(self):
  30. return next(self.itercycle)
  31. def merge(color_string):
  32. """ Given a string of colorama ANSI, merge them if you can. """
  33. return color_string.replace("m\x1b[", ";")
  34. class PlayerInput(object):
  35. """ Player Input
  36. Example:
  37. from flexible import PlayerInput
  38. ask = PlayerInput(self.game)
  39. # abort_blank means, if the input field is blank, abort. Use error_back.
  40. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  41. # Display the user's input / but not needed.
  42. d.addCallback(ask.output)
  43. d.addCallback(
  44. lambda ignore: ask.prompt(
  45. "What is your favorite color?", 10, name="color"
  46. )
  47. )
  48. d.addCallback(ask.output)
  49. d.addCallback(
  50. lambda ignore: ask.prompt(
  51. "What is your least favorite number?",
  52. 12,
  53. name="number",
  54. digits=True,
  55. )
  56. )
  57. d.addCallback(ask.output)
  58. def show_values(show):
  59. log.msg(show)
  60. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  61. d.addCallback(lambda ignore: show_values(ask.keep))
  62. d.addCallback(self.welcome_back)
  63. # On error, just return back
  64. d.addErrback(self.welcome_back)
  65. """
  66. def __init__(self, game):
  67. # I think game gives us access to everything we need
  68. self.game = game
  69. self.observer = self.game.observer
  70. self.save = None
  71. self.deferred = None
  72. self.queue_game = game.queue_game
  73. self.keep = {}
  74. # default colors
  75. self.c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  76. self.cp = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  77. # useful consts
  78. self.r = Style.RESET_ALL
  79. self.nl = "\n\r"
  80. self.bsb = "\b \b"
  81. self.keepalive = None
  82. def color(self, c):
  83. self.c = c
  84. def colorp(self, cp):
  85. self.cp = cp
  86. def alive(self):
  87. log.msg("PlayerInput.alive()")
  88. self.game.queue_player.put(" ")
  89. def prompt(self, user_prompt, limit, **kw):
  90. """ Generate prompt for user input.
  91. Note: This returns deferred.
  92. prompt = text displayed.
  93. limit = # of characters allowed.
  94. default = (text to default to)
  95. keywords:
  96. abort_blank : Abort if they give us blank text.
  97. name : Stores the input in self.keep dict.
  98. digits : Only allow 0-9 to be entered.
  99. """
  100. log.msg("PlayerInput({0}, {1}, {2}".format(user_prompt, limit, kw))
  101. self.limit = limit
  102. self.input = ""
  103. self.kw = kw
  104. assert self.save is None
  105. assert self.keepalive is None
  106. # Note: This clears out the server "keep alive"
  107. self.save = self.observer.save()
  108. self.observer.connect("player", self.get_input)
  109. self.keepalive = task.LoopingCall(self.alive)
  110. self.keepalive.start(30)
  111. # We need to "hide" the game output.
  112. # Otherwise it WITH mess up the user input display.
  113. self.to_player = self.game.to_player
  114. self.game.to_player = False
  115. # Display prompt
  116. # self.queue_game.put(self.r + self.nl + self.c + user_prompt + " " + self.cp)
  117. self.queue_game.put(self.r + self.c + user_prompt + self.r + " " + self.cp)
  118. # Set "Background of prompt"
  119. self.queue_game.put(" " * limit + "\b" * limit)
  120. assert self.deferred is None
  121. d = defer.Deferred()
  122. self.deferred = d
  123. log.msg("Return deferred ...", self.deferred)
  124. return d
  125. def get_input(self, chunk):
  126. """ Data from player (in bytes) """
  127. chunk = chunk.decode("latin-1", "ignore")
  128. for ch in chunk:
  129. if ch == "\b":
  130. if len(self.input) > 0:
  131. self.queue_game.put(self.bsb)
  132. self.input = self.input[0:-1]
  133. else:
  134. self.queue_game.put("\a")
  135. elif ch == "\r":
  136. self.queue_game.put(self.r + self.nl)
  137. log.msg("Restore observer dispatch", self.save)
  138. assert not self.save is None
  139. self.observer.load(self.save)
  140. self.save = None
  141. log.msg("Disable keepalive")
  142. self.keepalive.stop()
  143. self.keepalive = None
  144. line = self.input
  145. self.input = ""
  146. assert not self.deferred is None
  147. self.game.to_player = self.to_player
  148. # If they gave us the keyword name, save the value as that name
  149. if "name" in self.kw:
  150. self.keep[self.kw["name"]] = line
  151. if "abort_blank" in self.kw and self.kw["abort_blank"]:
  152. # Abort on blank input
  153. if line.strip() == "":
  154. # Yes, input is blank, abort.
  155. log.msg("errback, abort_blank")
  156. reactor.callLater(
  157. 0, self.deferred.errback, Exception("abort_blank")
  158. )
  159. self.deferred = None
  160. return
  161. # Ok, use deferred.callback, or reactor.callLater?
  162. # self.deferred.callback(line)
  163. reactor.callLater(0, self.deferred.callback, line)
  164. self.deferred = None
  165. return
  166. elif ch.isprintable():
  167. # Printable, but is it acceptable?
  168. if "digits" in self.kw:
  169. if not ch.isdigit():
  170. self.queue_game.put("\a")
  171. continue
  172. if len(self.input) + 1 <= self.limit:
  173. self.input += ch
  174. self.queue_game.put(ch)
  175. else:
  176. self.queue_game.put("\a")
  177. def output(self, line):
  178. """ A default display of what they just input. """
  179. log.msg("PlayerInput.output({0})".format(line))
  180. self.game.queue_game.put(self.r + "[{0}]".format(line) + self.nl)
  181. return line
  182. import re
  183. # The CIMWarpReport -- is only needed if the json file gets damaged in some way.
  184. # or needs to be reset. The warps should automatically update themselves now.
  185. class CIMWarpReport(object):
  186. def __init__(self, game):
  187. self.game = game
  188. self.queue_game = game.queue_game
  189. self.queue_player = game.queue_player
  190. self.observer = game.observer
  191. # Yes, at this point we would activate
  192. self.prompt = game.buffer
  193. self.save = self.observer.save()
  194. # I actually don't want the player input, but I'll grab it anyway.
  195. self.observer.connect("player", self.player)
  196. self.observer.connect("prompt", self.game_prompt)
  197. self.observer.connect("game-line", self.game_line)
  198. # If we want it, it's here.
  199. self.defer = None
  200. self.to_player = self.game.to_player
  201. # Hide what's happening from the player
  202. self.game.to_player = False
  203. self.queue_player.put("^") # Activate CIM
  204. self.state = 1
  205. # self.warpdata = {}
  206. self.warpcycle = SpinningCursor()
  207. def game_prompt(self, prompt):
  208. if prompt == ": ":
  209. if self.state == 1:
  210. # Ok, then we're ready to request the port report
  211. self.warpcycle.reset()
  212. self.queue_player.put("I")
  213. self.state = 2
  214. elif self.state == 2:
  215. self.queue_player.put("Q")
  216. self.state = 3
  217. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  218. if self.state == 3:
  219. # Ok, time to exit
  220. # exit from this...
  221. self.game.to_player = self.to_player
  222. self.observer.load(self.save)
  223. self.save = None
  224. # self.game.warpdata = self.warpdata
  225. self.queue_game.put("\b \b\r\n")
  226. if not self.defer is None:
  227. self.defer.callback(self.game.gamedata.warps)
  228. self.defer = None
  229. def game_line(self, line):
  230. if line == "" or line == ": ":
  231. return
  232. if line == ": ENDINTERROG":
  233. return
  234. if line.startswith('Command [TL='):
  235. return
  236. # This should be the CIM Report Data -- parse it
  237. if self.warpcycle:
  238. if self.warpcycle.click():
  239. self.queue_game.put("\b" + self.warpcycle.cycle())
  240. work = line.strip()
  241. parts = re.split(r"(?<=\d)\s", work)
  242. parts = [int(x) for x in parts]
  243. sector = parts.pop(0)
  244. # tuples are nicer on memory, and the warpdata map isn't going to be changing.
  245. # self.warpdata[sector] = tuple(parts)
  246. self.game.gamedata.warp_to(sector, *parts)
  247. def __del__(self):
  248. log.msg("CIMWarpReport {0} RIP".format(self))
  249. def whenDone(self):
  250. self.defer = defer.Deferred()
  251. # Call this to chain something after we exit.
  252. return self.defer
  253. def player(self, chunk):
  254. """ Data from player (in bytes). """
  255. chunk = chunk.decode("latin-1", "ignore")
  256. key = chunk.upper()
  257. log.msg("CIMWarpReport.player({0}) : I AM stopping...".format(key))
  258. # Stop the keepalive if we are activating something else
  259. # or leaving...
  260. # self.keepalive.stop()
  261. self.queue_game.put("\b \b\r\n")
  262. if not self.defer is None:
  263. # We have something, so:
  264. self.game.to_player = self.to_player
  265. self.observer.load(self.save)
  266. self.save = None
  267. self.defer.errback(Exception("User Abort"))
  268. self.defer = None
  269. else:
  270. # Still "exit" out.
  271. self.game.to_player = self.to_player
  272. self.observer.load(self.save)
  273. # the CIMPortReport will still be needed.
  274. # We can't get fresh report data (that changes) any other way.
  275. class CIMPortReport(object):
  276. """ Parse data from CIM Port Report
  277. Example:
  278. from flexible import CIMPortReport
  279. report = CIMPortReport(self.game)
  280. d = report.whenDone()
  281. d.addCallback(self.port_report)
  282. d.addErrback(self.welcome_back)
  283. def port_report(self, portdata):
  284. self.portdata = portdata
  285. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  286. self.welcome_back()
  287. def welcome_back(self,*_):
  288. ... restore keep alive timers, etc.
  289. """
  290. def __init__(self, game):
  291. self.game = game
  292. self.queue_game = game.queue_game
  293. self.queue_player = game.queue_player
  294. self.observer = game.observer
  295. # Yes, at this point we would activate
  296. self.prompt = game.buffer
  297. self.save = self.observer.save()
  298. # I actually don't want the player input, but I'll grab it anyway.
  299. self.observer.connect("player", self.player)
  300. self.observer.connect("prompt", self.game_prompt)
  301. self.observer.connect("game-line", self.game_line)
  302. # If we want it, it's here.
  303. self.defer = None
  304. self.to_player = self.game.to_player
  305. log.msg("to_player (stored)", self.to_player)
  306. # Hide what's happening from the player
  307. self.game.to_player = False
  308. self.queue_player.put("^") # Activate CIM
  309. self.state = 1
  310. # self.portdata = {}
  311. self.portcycle = SpinningCursor()
  312. def game_prompt(self, prompt):
  313. if prompt == ": ":
  314. if self.state == 1:
  315. # Ok, then we're ready to request the port report
  316. self.portcycle.reset()
  317. self.queue_player.put("R")
  318. self.state = 2
  319. elif self.state == 2:
  320. self.queue_player.put("Q")
  321. self.state = 3
  322. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  323. if self.state == 3:
  324. # Ok, time to exit
  325. # exit from this...
  326. self.game.to_player = self.to_player
  327. self.observer.load(self.save)
  328. self.save = None
  329. # self.game.portdata = self.portdata
  330. self.queue_game.put("\b \b\r\n")
  331. if not self.defer is None:
  332. self.defer.callback(self.game.gamedata.ports)
  333. self.defer = None
  334. def game_line(self, line: str):
  335. if line == "" or line == ": ":
  336. return
  337. if line == ": ENDINTERROG":
  338. return
  339. # This should be the CIM Report Data -- parse it
  340. if self.portcycle:
  341. if self.portcycle.click():
  342. self.queue_game.put("\b" + self.portcycle.cycle())
  343. work = line.replace("%", "")
  344. parts = re.split(r"(?<=\d)\s", work)
  345. if len(parts) == 8:
  346. port = int(parts[0].strip())
  347. data = dict()
  348. def portBS(info):
  349. if info[0] == "-":
  350. bs = "B"
  351. else:
  352. bs = "S"
  353. return (bs, int(info[1:].strip()))
  354. data["fuel"] = dict()
  355. data["fuel"]["sale"], data["fuel"]["units"] = portBS(parts[1])
  356. data["fuel"]["pct"] = int(parts[2].strip())
  357. data["org"] = dict()
  358. data["org"]["sale"], data["org"]["units"] = portBS(parts[3])
  359. data["org"]["pct"] = int(parts[4].strip())
  360. data["equ"] = dict()
  361. data["equ"]["sale"], data["equ"]["units"] = portBS(parts[5])
  362. data["equ"]["pct"] = int(parts[6].strip())
  363. # Store what this port is buying/selling
  364. data["port"] = (
  365. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  366. )
  367. # Convert BBS/SBB to Class number 1-8
  368. data["class"] = CLASSES_PORT[data["port"]]
  369. self.game.gamedata.set_port(port, data)
  370. # self.portdata[port] = data
  371. else:
  372. log.msg("CIMPortReport:", line, "???")
  373. def __del__(self):
  374. log.msg("CIMPortReport {0} RIP".format(self))
  375. def whenDone(self):
  376. self.defer = defer.Deferred()
  377. # Call this to chain something after we exit.
  378. return self.defer
  379. def player(self, chunk):
  380. """ Data from player (in bytes). """
  381. chunk = chunk.decode("latin-1", "ignore")
  382. key = chunk.upper()
  383. log.msg("CIMPortReport.player({0}) : I AM stopping...".format(key))
  384. # Stop the keepalive if we are activating something else
  385. # or leaving...
  386. # self.keepalive.stop()
  387. self.queue_game.put("\b \b\r\n")
  388. if not self.defer is None:
  389. # We have something, so:
  390. self.game.to_player = self.to_player
  391. self.observer.load(self.save)
  392. self.save = None
  393. self.defer.errback(Exception("User Abort"))
  394. self.defer = None
  395. else:
  396. # Still "exit" out.
  397. self.game.to_player = self.to_player
  398. self.observer.load(self.save)
  399. class ScriptPort(object):
  400. """ Performs the Port script.
  401. This is close to the original.
  402. We don't ask for the port to trade with --
  403. because that information is available to us after "D" (display).
  404. We look at the adjacent sectors, and see if we know any ports.
  405. If the ports are burnt (< 20%), we remove them from the list.
  406. If there's just one, we use it. Otherwise we ask them to choose.
  407. """
  408. def __init__(self, game):
  409. self.game = game
  410. self.queue_game = game.queue_game
  411. self.queue_player = game.queue_player
  412. self.observer = game.observer
  413. self.r = Style.RESET_ALL
  414. self.nl = "\n\r"
  415. self.this_sector = None # Starting sector
  416. self.sector1 = None # Current Sector
  417. self.sector2 = None # Next Sector Stop
  418. self.percent = 5 # Stick with the good default.
  419. self.credits = 0
  420. self.last_credits = None
  421. self.times_left = 0
  422. # Activate
  423. self.prompt = game.buffer
  424. self.save = self.observer.save()
  425. self.observer.connect('player', self.player)
  426. self.observer.connect("prompt", self.game_prompt)
  427. self.observer.connect("game-line", self.game_line)
  428. self.defer = None
  429. self.queue_game.put(
  430. self.nl + "Script based on: Port Pair Trading v2.00" + self.r + self.nl
  431. )
  432. self.possible_sectors = None
  433. self.state = 1
  434. self.queue_player.put("D")
  435. # Original, send 'D' to display current sector.
  436. # We could get the sector number from the self.prompt string -- HOWEVER:
  437. # IF! We send 'D', we can also get the sectors around -- we might not even need to
  438. # prompt for sector to trade with (we could possibly figure it out ourselves).
  439. # [Command [TL=00:00:00]:[967] (?=Help)? : D]
  440. # [<Re-Display>]
  441. # []
  442. # [Sector : 967 in uncharted space.]
  443. # [Planets : (M) Into the Darkness]
  444. # [Warps to Sector(s) : 397 - (562) - (639)]
  445. # []
  446. def whenDone(self):
  447. self.defer = defer.Deferred()
  448. # Call this to chain something after we exit.
  449. return self.defer
  450. def deactivate(self):
  451. self.state = 0
  452. log.msg("ScriptPort.deactivate ({0})".format(self.times_left))
  453. assert(not self.save is None)
  454. self.observer.load(self.save)
  455. self.save = None
  456. if self.defer:
  457. self.defer.callback('done')
  458. self.defer = None
  459. def player(self, chunk: bytes):
  460. # If we receive anything -- ABORT!
  461. self.deactivate()
  462. def game_prompt(self, prompt: str):
  463. log.msg("{0} : {1}".format(self.state, prompt))
  464. if self.state == 3:
  465. log.msg("game_prompt: ", prompt)
  466. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  467. self.state = 4
  468. log.msg("Ok, state 4")
  469. if self.sector2 is None:
  470. # Ok, we need to prompt for this.
  471. self.queue_game.put(self.r + self.nl +
  472. "Which sector to trade with? {0}".format(GameData.port_show_part(self.this_sector, self.game.gamedata.ports[self.this_sector])) +
  473. self.nl + Fore.CYAN)
  474. for i, p in enumerate(self.possible):
  475. self.queue_game.put(" " + str(i + 1) + " : " + GameData.port_show_part(p, self.game.gamedata.ports[p]) + self.nl)
  476. pi = PlayerInput(self.game)
  477. def got_need1(*_):
  478. log.msg("Ok, I have:", pi.keep)
  479. if pi.keep['count'].strip() == '':
  480. self.deactivate()
  481. return
  482. self.times_left = int(pi.keep['count'])
  483. if pi.keep['choice'].strip() == '':
  484. self.deactivate()
  485. return
  486. c = int(pi.keep['choice']) -1
  487. if c < 0 or c >= len(self.possible):
  488. self.deactivate()
  489. return
  490. self.sector2 = self.possible[int(pi.keep['choice']) -1]
  491. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  492. self.state = 5
  493. self.trade()
  494. d = pi.prompt("Choose -=>", 5, name='choice', digits=True)
  495. d.addCallback(lambda ignore: pi.prompt("Times to execute script:", 5, name='count', digits=True))
  496. d.addCallback(got_need1)
  497. else:
  498. # We already have our target port, so...
  499. self.queue_game.put(self.r + self.nl + "Trading from {0} ({1}) to default {2} ({3}).".format(
  500. self.this_sector,
  501. self.game.gamedata.ports[self.this_sector]['port'],
  502. self.sector2, self.game.gamedata.ports[self.sector2]['port']) + self.nl
  503. )
  504. self.queue_game.put(self.r + self.nl + "Trading {0}".format(
  505. GameData.port_show(self.this_sector,
  506. self.game.gamedata.ports[self.this_sector],
  507. self.sector2,
  508. self.game.gamedata.ports[self.sector2])
  509. ))
  510. # The code is smart enough now, that this can't happen. :( Drat!
  511. if self.game.gamedata.ports[self.this_sector]['port'] == self.game.gamedata.ports[self.sector2]['port']:
  512. self.queue_game.put("Hey dummy! Look out the window! These ports are the same class!" + nl)
  513. self.deactivate()
  514. return
  515. pi = PlayerInput(self.game)
  516. def got_need2(*_):
  517. if pi.keep['count'].strip() == '':
  518. self.deactivate()
  519. return
  520. self.times_left = int(pi.keep['count'])
  521. log.msg("Ok, I have:", pi.keep)
  522. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  523. self.state = 5
  524. self.trade()
  525. self.queue_game.put(self.r + self.nl)
  526. d = pi.prompt("Times to execute script", 5, name='count')
  527. d.addCallback(got_need2)
  528. elif self.state == 6:
  529. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  530. if self.fixable:
  531. log.msg("Fixing...")
  532. if self.this_sector == self.sector1:
  533. self.this_sector = self.sector2
  534. self.queue_player.put("{0}\r".format(self.sector2))
  535. self.state = 5
  536. self.trade()
  537. else:
  538. self.this_sector = self.sector1
  539. self.queue_player.put("{0}\r".format(self.sector1))
  540. self.state = 5
  541. self.trade()
  542. elif self.state == 7:
  543. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  544. # Done
  545. if self.this_sector == self.sector1:
  546. self.this_sector = self.sector2
  547. self.queue_player.put("{0}\r".format(self.sector2))
  548. self.state = 10
  549. else:
  550. self.times_left -= 1
  551. if self.times_left <= 0:
  552. # Ok, exit out
  553. self.deactivate()
  554. return
  555. if self.last_credits is None:
  556. self.last_credits = self.credits
  557. else:
  558. if self.credits <= self.last_credits:
  559. log.msg("We don't seem to be making any money here...")
  560. self.queue_game.put(self.r + self.nl + "We don't seem to be making any money here. I'm stopping!" + self.nl)
  561. self.deactivate()
  562. return
  563. self.this_sector = self.sector1
  564. self.queue_player.put("{0}\r".format(self.sector1))
  565. self.state = 10
  566. elif re.match(r'Your offer \[\d+\] \?', prompt):
  567. if self.fix_offer:
  568. # Make real offer / WHAT?@?!
  569. work = prompt.replace(',', '')
  570. parts = re.split(r"\s+", work)
  571. amount = parts[2]
  572. # Ok, we have the amount, now to figure pct...
  573. if self.sell_pct > 100:
  574. self.sell_pct -= 1
  575. else:
  576. self.sell_pct += 1
  577. price = amount * self.sell_pct // 100
  578. log.msg("start: {0} % {1} price {2}".format(amount, self.sell_perc, price))
  579. if self.sell_pct > 100:
  580. self.sell_pct -= 1
  581. else:
  582. self.sell_pct += 1
  583. self.queue_player.put("{0}\r".format(price))
  584. elif self.state == 8:
  585. # What are we trading
  586. # How many holds of Equipment do you want to buy [75]?
  587. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\?", prompt):
  588. parts = prompt.split()
  589. trade_type = parts[4]
  590. if trade_type == 'Fuel':
  591. if (self.tpc in (5,7)) and (self.opc in (2,3,4,8)):
  592. # Can buy equipment - fuel ore is worthless.
  593. self.queue_player.put("0\r")
  594. return
  595. if (self.tpc in(4,7)) and (self.opc in (1,3,5,8)):
  596. # Can buy organics - fuel ore is worthless.
  597. self.queue_player.put("0\r")
  598. return
  599. if (self.tpc in (4,7,3,5)) and (self.opc in (3,4,5,7)):
  600. # No point in buying fuel ore if it can't be sold.
  601. self.queue_player.put("0\r")
  602. return
  603. elif trade_type == 'Organics':
  604. if (self.tpc in (6,7)) and (self.opc in (2,3,4,8)):
  605. # Can buy equipment - organics is worthless.
  606. self.queue_player.put("0\r")
  607. return
  608. if (self.tpc in (2,4,6,7)) and (self.opc in (2,4,6,7)):
  609. # No point in buying organics if it can't be sold.
  610. self.queue_player.put("0\r")
  611. return
  612. elif trade_type == 'Equipment':
  613. if (self.opc in (1,5,6,7)):
  614. # No point in buying equipment if it can't be sold.
  615. self.queue_player.put("0\r")
  616. return
  617. self.queue_player.put("\r")
  618. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  619. # Done
  620. if self.this_sector == self.sector1:
  621. self.this_sector = self.sector2
  622. self.queue_player.put("{0}\r".format(self.sector2))
  623. self.state = 10
  624. else:
  625. self.times_left -= 1
  626. if self.times_left <= 0:
  627. # Ok, exit out
  628. self.deactivate()
  629. return
  630. if self.last_credits is None:
  631. self.last_credits = self.credits
  632. else:
  633. if self.credits <= self.last_credits:
  634. log.msg("We don't seem to be making any money here...")
  635. self.deactivate()
  636. return
  637. self.this_sector = self.sector1
  638. self.queue_player.put("{0}\r".format(self.sector1))
  639. self.state = 10
  640. def trade(self, *_):
  641. # state 5
  642. log.msg("trade!")
  643. self.queue_player.put("pt") # Port Trade
  644. self.this_port = self.game.gamedata.ports[self.this_sector]
  645. if self.this_sector == self.sector1:
  646. self.other_port = self.game.gamedata.ports[self.sector2]
  647. else:
  648. self.other_port = self.game.gamedata.ports[self.sector1]
  649. # Ok, perform some calculations
  650. self.tpc = self.this_port['class']
  651. self.opc = self.other_port['class']
  652. self.fixable = 0
  653. self.fix_offer = 0
  654. # [ Items Status Trading % of max OnBoard]
  655. # [ ----- ------ ------- -------- -------]
  656. # [Fuel Ore Selling 2573 93% 0]
  657. # [Organics Buying 2960 100% 0]
  658. # [Equipment Buying 1958 86% 0]
  659. # []
  660. # []
  661. # [You have 1,000 credits and 20 empty cargo holds.]
  662. # []
  663. # [We are selling up to 2573. You have 0 in your holds.]
  664. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  665. def game_line(self, line: str):
  666. if line.startswith("You have ") and 'credits and' in line:
  667. parts = line.replace(',', '').split()
  668. credits = int(parts[2])
  669. log.msg("Credits: {0}".format(credits))
  670. self.credits = credits
  671. if self.state == 1:
  672. # First exploration
  673. if line.startswith("Sector :"):
  674. # We have starting sector information
  675. parts = re.split("\s+", line)
  676. self.this_sector = int(parts[2])
  677. # These will be the ones swapped around as we trade back and forth.
  678. self.sector1 = self.this_sector
  679. elif line.startswith("Warps to Sector(s) : "):
  680. # Warps to Sector(s) : 397 - (562) - (639)
  681. _, _, warps = line.partition(':')
  682. warps = warps.replace('-', '').replace('(', '').replace(')', '').strip()
  683. log.msg("Warps: [{0}]".format(warps))
  684. self.warps = [ int(x) for x in re.split("\s+", warps)]
  685. log.msg("Warps: [{0}]".format(self.warps))
  686. self.state = 2
  687. elif self.state == 2:
  688. if line == "":
  689. # Ok, we're done
  690. self.state = 3
  691. # Check to see if we have information on any possible ports
  692. # if hasattr(self.game, 'portdata'):
  693. if True:
  694. if not self.this_sector in self.game.gamedata.ports:
  695. self.state = 0
  696. log.msg("Current sector {0} not in portdata.".format(self.this_sector))
  697. self.queue_game.put(self.r + self.nl + "I can't find the current sector in the portdata." + self.nl)
  698. self.deactivate()
  699. return
  700. else:
  701. # Ok, we are in the portdata
  702. pd = self.game.gamedata.ports[self.this_sector]
  703. if GameData.port_burnt(pd):
  704. log.msg("Current sector {0} port is burnt (<= 20%).".format(self.this_sector))
  705. self.queue_game.put(self.r + self.nl + "Current sector port is burnt out. <= 20%." + self.nl)
  706. self.deactivate()
  707. return
  708. possible = [ x for x in self.warps if x in self.game.gamedata.ports ]
  709. log.msg("Possible:", possible)
  710. # BUG: Sometimes links to another sector, don't link back!
  711. # This causes the game to plot a course / autopilot.
  712. # if hasattr(self.game, 'warpdata'):
  713. if True:
  714. # Great! verify that those warps link back to us!
  715. possible = [ x for x in possible if x in self.game.gamedata.warps and self.this_sector in self.game.gamedata.warps[x]]
  716. if len(possible) == 0:
  717. self.state = 0
  718. self.queue_game.put(self.r + self.nl + "I don't see any ports in [{0}].".format(self.warps) + self.nl)
  719. self.deactivate()
  720. return
  721. possible = [ x for x in possible if not GameData.port_burnt(self.game.gamedata.ports[x]) ]
  722. log.msg("Possible:", possible)
  723. if len(possible) == 0:
  724. self.state = 0
  725. self.queue_game.put(self.r + self.nl + "I don't see any unburnt ports in [{0}].".format(self.warps) + self.nl)
  726. self.deactivate()
  727. return
  728. possible = [ x for x in possible if port_trading(self.game.gamedata.ports[self.this_sector]['port'], self.game.gamedata.ports[x]['port'])]
  729. self.possible = possible
  730. if len(possible) == 0:
  731. self.state = 0
  732. self.queue_game.put(self.r + self.nl + "I don't see any possible port trades in [{0}].".format(self.warps) + self.nl)
  733. self.deactivate()
  734. return
  735. elif len(possible) == 1:
  736. # Ok! there's only one!
  737. self.sector2 = possible[0]
  738. # Display possible ports:
  739. # spos = [ str(x) for x in possible]
  740. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  741. # At state 3, we only get a prompt.
  742. return
  743. else:
  744. self.state = 0
  745. log.msg("We don't have any portdata!")
  746. self.queue_game.put(self.r + self.nl + "I have no portdata. Please run CIM Port Report." + self.nl)
  747. self.deactivate()
  748. return
  749. elif self.state == 5:
  750. if "-----" in line:
  751. self.state = 6
  752. elif self.state == 6:
  753. if "We are buying up to" in line:
  754. # Sell
  755. self.state = 7
  756. self.queue_player.put("\r")
  757. self.sell_perc = 100 + self.percent
  758. if "We are selling up to" in line:
  759. # Buy
  760. self.state = 8
  761. self.sell_perc = 100 - self.percent
  762. if line.startswith('Fuel Ore') or line.startswith('Organics') or line.startswith('Equipment'):
  763. work = line.replace('Fuel Ore', 'Fuel')
  764. parts = re.split(r"\s+", work)
  765. # log.msg(parts)
  766. # Equipment, Selling xxx x% xxx
  767. if parts[-1] != '0' and parts[2] != '0' and parts[1] != 'Buying':
  768. log.msg("We have a problem -- they aren't buying what we have in stock!")
  769. stuff = line[0] # F O or E.
  770. if stuff == 'F':
  771. spos = 0
  772. elif stuff == 'O':
  773. spos = 1
  774. else:
  775. spos = 2
  776. other = self.other_port['port']
  777. if other[spos] == 'B':
  778. self.fixable = 1
  779. if "You don't have anything they want" in line:
  780. # Neither! DRAT!
  781. if not self.fixable:
  782. self.deactivate()
  783. return
  784. if "We're not interested." in line:
  785. log.msg("Try, try again. :(")
  786. self.state = 5
  787. self.trade()
  788. elif self.state == 7:
  789. # Haggle Sell
  790. if "We'll buy them for" in line or "Our final offer" in line:
  791. if "Our final offer" in line:
  792. self.sell_perc -= 1
  793. parts = line.replace(',', '').split()
  794. start_price = int(parts[4])
  795. price = start_price * self.sell_perc // 100
  796. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  797. self.sell_perc -= 1
  798. self.queue_player.put("{0}\r".format(price))
  799. if "We are selling up to" in line:
  800. # Buy
  801. self.state = 8
  802. self.sell_perc = 100 - self.percent
  803. if "We're not interested." in line:
  804. log.msg("Try, try again. :(")
  805. self.state = 5
  806. self.trade()
  807. if "WHAT?!@!? you must be crazy!" in line:
  808. log.msg("fix offer")
  809. self.fix_offer = 1
  810. if "So, you think I'm as stupid as you look?" in line:
  811. log.msg("fix offer")
  812. self.fix_offer = 1
  813. if "Quit playing around, you're wasting my time!" in line:
  814. log.msg("fix offer")
  815. self.fix_offer = 1
  816. elif self.state == 8:
  817. # Haggle Buy
  818. if "We'll sell them for" in line or "Our final offer" in line:
  819. if "Our final offer" in line:
  820. self.sell_perc += 1
  821. parts = line.replace(',', '').split()
  822. start_price = int(parts[4])
  823. price = start_price * self.sell_perc // 100
  824. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  825. self.sell_perc += 1
  826. self.queue_player.put("{0}\r".format(price))
  827. if "We're not interested." in line:
  828. log.msg("Try, try again. :(")
  829. self.state = 5
  830. self.trade()
  831. elif self.state == 10:
  832. if "Sector : " in line:
  833. # Trade
  834. self.state = 5
  835. reactor.callLater(0, self.trade, 0)
  836. # self.trade()
  837. # elif self.state == 3:
  838. # log.msg("At state 3 [{0}]".format(line))
  839. # self.queue_game.put("At state 3.")
  840. # self.deactivate()
  841. # return
  842. class ProxyMenu(object):
  843. """ Display ProxyMenu
  844. Example:
  845. from flexible import ProxyMenu
  846. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  847. menu = ProxyMenu(self.game)
  848. """
  849. def __init__(self, game):
  850. self.nl = "\n\r"
  851. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  852. self.r = Style.RESET_ALL
  853. self.c1 = merge(Style.BRIGHT + Fore.BLUE)
  854. self.c2 = merge(Style.NORMAL + Fore.CYAN)
  855. # self.portdata = None
  856. self.game = game
  857. self.queue_game = game.queue_game
  858. self.observer = game.observer
  859. # Am I using self or game? (I think I want game, not self.)
  860. # if hasattr(self.game, "portdata"):
  861. # self.portdata = self.game.portdata
  862. # else:
  863. # self.portdata = {}
  864. # if hasattr(self.game, 'warpdata'):
  865. # self.warpdata = self.game.warpdata
  866. # else:
  867. # self.warpdata = {}
  868. if hasattr(self.game, 'trade_report'):
  869. self.trade_report = self.game.trade_report
  870. else:
  871. self.trade_report = []
  872. # Yes, at this point we would activate
  873. self.prompt = game.buffer
  874. self.save = self.observer.save()
  875. self.observer.connect("player", self.player)
  876. # If we want it, it's here.
  877. self.defer = None
  878. self.keepalive = task.LoopingCall(self.awake)
  879. self.keepalive.start(30)
  880. self.menu()
  881. def __del__(self):
  882. log.msg("ProxyMenu {0} RIP".format(self))
  883. def whenDone(self):
  884. self.defer = defer.Deferred()
  885. # Call this to chain something after we exit.
  886. return self.defer
  887. def menu(self):
  888. self.queue_game.put(
  889. self.nl + self.c + "TradeWars Proxy active." + self.r + self.nl
  890. )
  891. def menu_item(ch: str, desc: str):
  892. self.queue_game.put(
  893. " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  894. )
  895. menu_item("D", "Display Report again")
  896. # menu_item("Q", "Quest")
  897. # if hasattr(self.game, 'portdata'):
  898. # ports = len(self.game.portdata)
  899. # else:
  900. # ports = '?'
  901. menu_item("P", "Port CIM Report ({0})".format(len(self.game.gamedata.ports)))
  902. # if hasattr(self.game, 'warpdata'):
  903. # warps = len(self.game.warpdata)
  904. # else:
  905. # warps = '?'
  906. menu_item("W", "Warp CIM Report ({0})".format(len(self.game.gamedata.warps)))
  907. menu_item("T", "Trading Report")
  908. menu_item("S", "Scripts")
  909. menu_item("X", "eXit")
  910. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  911. def awake(self):
  912. log.msg("ProxyMenu.awake()")
  913. self.game.queue_player.put(" ")
  914. def port_report(self, portdata: dict):
  915. # self.portdata = portdata
  916. # self.game.portdata = portdata
  917. self.queue_game.put("Loaded {0} ports.".format(len(portdata)) + self.nl)
  918. self.welcome_back()
  919. def warp_report(self, warpdata: dict):
  920. # self.warpdata = warpdata
  921. # self.game.warpdata = warpdata
  922. self.queue_game.put("Loaded {0} sectors.".format(len(warpdata)) + self.nl)
  923. self.welcome_back()
  924. def make_trade_report(self):
  925. log.msg("make_trade_report()")
  926. ok_trades = []
  927. best_trades = []
  928. # for sector, pd in self.game.gamedata.ports.items():
  929. for sector in sorted(self.game.gamedata.ports.keys()):
  930. pd = self.game.gamedata.ports[sector]
  931. if not GameData.port_burnt(pd):
  932. pc = pd['class']
  933. # Ok, let's look into it.
  934. if not sector in self.game.gamedata.warps:
  935. continue
  936. warps = self.game.gamedata.warps[sector]
  937. for w in warps:
  938. # Verify that we have that warp's info, and that the sector is in it.
  939. # (We can get back from it)
  940. if w in self.game.gamedata.warps and sector in self.game.gamedata.warps[w]:
  941. # Ok, we can get there -- and get back!
  942. if w > sector and w in self.game.gamedata.ports and not GameData.port_burnt(self.game.gamedata.ports[w]):
  943. # it is > and has a port.
  944. wd = self.game.gamedata.ports[w]
  945. wc = wd['class']
  946. # 1: "BBS",
  947. # 2: "BSB",
  948. # 3: "SBB",
  949. # 4: "SSB",
  950. # 5: "SBS",
  951. # 6: "BSS",
  952. # 7: "SSS",
  953. # 8: "BBB",
  954. if pc in (1,5) and wc in (2,4):
  955. best_trades.append(self.game.gamedata.port_trade_show(sector, w))
  956. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  957. elif pc in (2,4) and wc in (1,5):
  958. best_trades.append(self.game.gamedata.port_trade_show(sector, w))
  959. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  960. elif GameData.port_trading(pd['port'], self.game.gamedata.ports[w]['port']):
  961. # ok_trades.append( "{0:5} -=- {1:5}".format(sector,w))
  962. ok_trades.append(GameData.port_show(sector, pd, w, wd))
  963. yield
  964. self.trade_report.append("Best Trades: (org/equ)")
  965. self.trade_report.extend(best_trades)
  966. self.trade_report.append("Ok Trades:")
  967. self.trade_report.extend(ok_trades)
  968. # self.queue_game.put("BEST TRADES:" + self.nl + self.nl.join(best_trades) + self.nl)
  969. # self.queue_game.put("OK TRADES:" + self.nl + self.nl.join(ok_trades) + self.nl)
  970. def show_trade_report(self, *_):
  971. self.game.trade_report = self.trade_report
  972. for t in self.trade_report:
  973. self.queue_game.put(t + self.nl)
  974. self.welcome_back()
  975. def player(self, chunk: bytes):
  976. """ Data from player (in bytes). """
  977. chunk = chunk.decode("latin-1", "ignore")
  978. key = chunk.upper()
  979. log.msg("ProxyMenu.player({0})".format(key))
  980. # Stop the keepalive if we are activating something else
  981. # or leaving...
  982. self.keepalive.stop()
  983. if key == "T":
  984. self.queue_game.put(self.c + key + self.r + self.nl)
  985. # Trade Report
  986. # do we have enough information to do this?
  987. # if not hasattr(self.game, 'portdata') and not hasattr(self.game, 'warpdata'):
  988. # self.queue_game.put("Missing portdata and warpdata." + self.nl)
  989. # elif not hasattr(self.game, 'portdata'):
  990. # self.queue_game.put("Missing portdata." + self.nl)
  991. # elif not hasattr(self.game, 'warpdata'):
  992. # self.queue_game.put("Missing warpdata." + self.nl)
  993. # else:
  994. if True:
  995. # Yes, so let's start!
  996. self.trade_report = []
  997. d = coiterate(self.make_trade_report())
  998. d.addCallback(self.show_trade_report)
  999. return
  1000. elif key == "P":
  1001. self.queue_game.put(self.c + key + self.r + self.nl)
  1002. # Activate CIM Port Report
  1003. report = CIMPortReport(self.game)
  1004. d = report.whenDone()
  1005. d.addCallback(self.port_report)
  1006. d.addErrback(self.welcome_back)
  1007. return
  1008. elif key == "W":
  1009. self.queue_game.put(self.c + key + self.r + self.nl)
  1010. # Activate CIM Warp Report
  1011. report = CIMWarpReport(self.game)
  1012. d = report.whenDone()
  1013. d.addCallback(self.warp_report)
  1014. d.addErrback(self.welcome_back)
  1015. return
  1016. elif key == "S":
  1017. self.queue_game.put(self.c + key + self.r + self.nl)
  1018. # Scripts
  1019. self.activate_scripts_menu()
  1020. return
  1021. elif key == "D":
  1022. self.queue_game.put(self.c + key + self.r + self.nl)
  1023. # (Re) Display Trade Report
  1024. if self.trade_report:
  1025. for t in self.trade_report:
  1026. self.queue_game.put(t + self.nl)
  1027. else:
  1028. self.queue_game.put("Missing trade_report." + self.nl)
  1029. # self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  1030. # self.queue_game.put(pformat(self.warpdata).replace("\n", "\n\r") + self.nl)
  1031. elif key == "Q":
  1032. self.queue_game.put(self.c + key + self.r + self.nl)
  1033. # This is an example of chaining PlayerInput prompt calls.
  1034. ask = PlayerInput(self.game)
  1035. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  1036. # Display the user's input
  1037. d.addCallback(ask.output)
  1038. d.addCallback(
  1039. lambda ignore: ask.prompt(
  1040. "What is your favorite color?", 10, name="color"
  1041. )
  1042. )
  1043. d.addCallback(ask.output)
  1044. d.addCallback(
  1045. lambda ignore: ask.prompt(
  1046. "What is the meaning of the squirrel?",
  1047. 12,
  1048. name="squirrel",
  1049. digits=True,
  1050. )
  1051. )
  1052. d.addCallback(ask.output)
  1053. def show_values(show):
  1054. log.msg(show)
  1055. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  1056. d.addCallback(lambda ignore: show_values(ask.keep))
  1057. d.addCallback(self.welcome_back)
  1058. # On error, just return back
  1059. # This doesn't seem to be getting called.
  1060. # d.addErrback(lambda ignore: self.welcome_back)
  1061. d.addErrback(self.welcome_back)
  1062. return
  1063. elif key == "X":
  1064. self.queue_game.put(self.c + key + self.r + self.nl)
  1065. self.queue_game.put("Proxy done." + self.nl)
  1066. self.observer.load(self.save)
  1067. self.save = None
  1068. # It isn't running (NOW), so don't try to stop it.
  1069. # self.keepalive.stop()
  1070. self.keepalive = None
  1071. # Ok, this is a HORRIBLE idea, because the prompt might be
  1072. # outdated.
  1073. # self.queue_game.put(self.prompt)
  1074. self.prompt = None
  1075. # Possibly: Send '\r' to re-display the prompt
  1076. # instead of displaying the original one.
  1077. self.game.queue_player.put("d")
  1078. # Were we asked to do something when we were done here?
  1079. if self.defer:
  1080. reactor.CallLater(0, self.defer.callback)
  1081. # self.defer.callback()
  1082. self.defer = None
  1083. return
  1084. self.keepalive.start(30, True)
  1085. self.menu()
  1086. def activate_scripts_menu(self):
  1087. self.observer.disconnect("player", self.player)
  1088. self.observer.connect("player", self.scripts_player)
  1089. self.scripts_menu()
  1090. def deactivate_scripts_menu(self, *_):
  1091. self.observer.disconnect("player", self.scripts_player)
  1092. self.observer.connect("player", self.player)
  1093. self.welcome_back()
  1094. def scripts_menu(self, *_):
  1095. c1 = merge(Style.BRIGHT + Fore.CYAN)
  1096. c2 = merge(Style.NORMAL + Fore.CYAN)
  1097. def menu_item(ch, desc):
  1098. self.queue_game.put(
  1099. " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  1100. )
  1101. menu_item("1", "Ports (Trades between two sectors)")
  1102. menu_item("2", "TODO")
  1103. menu_item("3", "TODO")
  1104. menu_item("X", "eXit")
  1105. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  1106. def scripts_player(self, chunk: bytes):
  1107. """ Data from player (in bytes). """
  1108. chunk = chunk.decode("latin-1", "ignore")
  1109. key = chunk.upper()
  1110. if key == '1':
  1111. self.queue_game.put(self.c + key + self.r + self.nl)
  1112. # Activate this magical event here
  1113. ports = ScriptPort(self.game)
  1114. d = ports.whenDone()
  1115. # d.addCallback(self.scripts_menu)
  1116. # d.addErrback(self.scripts_menu)
  1117. d.addCallback(self.deactivate_scripts_menu)
  1118. d.addErrback(self.deactivate_scripts_menu)
  1119. return
  1120. elif key == 'X':
  1121. self.queue_game.put(self.c + key + self.r + self.nl)
  1122. self.deactivate_scripts_menu()
  1123. return
  1124. else:
  1125. self.queue_game.put(self.c + "?" + self.r + self.nl)
  1126. self.scripts_menu()
  1127. def welcome_back(self, *_):
  1128. log.msg("welcome_back")
  1129. self.keepalive.start(30, True)
  1130. self.menu()