flexible.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
  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. from boxes import Boxes
  13. import logging
  14. log = logging.getLogger(__name__)
  15. class SpinningCursor(object):
  16. """ Spinner class, that handles every so many clicks
  17. s = SpinningCursor(5) # every 5
  18. for x in range(10):
  19. if s.click():
  20. print(s.cycle())
  21. """
  22. def __init__(self, every=10):
  23. self.itercycle = cycle(["/", "-", "\\", "|"])
  24. self.count = 0
  25. self.every = every
  26. def reset(self):
  27. self.itercycle = cycle(["/", "-", "\\", "|"])
  28. self.count = 0
  29. def click(self):
  30. self.count += 1
  31. return self.count % self.every == 0
  32. def cycle(self):
  33. return next(self.itercycle)
  34. def merge(color_string):
  35. """ Given a string of colorama ANSI, merge them if you can. """
  36. return color_string.replace("m\x1b[", ";")
  37. class PlayerInput(object):
  38. """ Player Input
  39. Example:
  40. from flexible import PlayerInput
  41. ask = PlayerInput(self.game)
  42. # abort_blank means, if the input field is blank, abort. Use error_back.
  43. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  44. # Display the user's input / but not needed.
  45. d.addCallback(ask.output)
  46. d.addCallback(
  47. lambda ignore: ask.prompt(
  48. "What is your favorite color?", 10, name="color"
  49. )
  50. )
  51. d.addCallback(ask.output)
  52. d.addCallback(
  53. lambda ignore: ask.prompt(
  54. "What is your least favorite number?",
  55. 12,
  56. name="number",
  57. digits=True,
  58. )
  59. )
  60. d.addCallback(ask.output)
  61. def show_values(show):
  62. log.debug(show)
  63. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  64. d.addCallback(lambda ignore: show_values(ask.keep))
  65. d.addCallback(self.welcome_back)
  66. # On error, just return back
  67. d.addErrback(self.welcome_back)
  68. """
  69. def __init__(self, game):
  70. # I think game gives us access to everything we need
  71. self.game = game
  72. self.observer = self.game.observer
  73. self.save = None
  74. self.deferred = None
  75. self.queue_game = game.queue_game
  76. self.keep = {}
  77. # default colors
  78. self.c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  79. self.cp = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  80. # useful constants
  81. self.r = Style.RESET_ALL
  82. self.nl = "\n\r"
  83. self.bsb = "\b \b"
  84. self.keepalive = None
  85. def color(self, c):
  86. self.c = c
  87. def colorp(self, cp):
  88. self.cp = cp
  89. def alive(self):
  90. log.debug("PlayerInput.alive()")
  91. self.game.queue_player.put(" ")
  92. def prompt(self, user_prompt, limit, **kw):
  93. """ Generate prompt for user input.
  94. Note: This returns deferred.
  95. prompt = text displayed.
  96. limit = # of characters allowed.
  97. default = (text to default to)
  98. keywords:
  99. abort_blank : Abort if they give us blank text.
  100. name : Stores the input in self.keep dict.
  101. digits : Only allow 0-9 to be entered.
  102. """
  103. log.debug("PlayerInput({0}, {1}, {2}".format(user_prompt, limit, kw))
  104. self.limit = limit
  105. self.input = ""
  106. self.kw = kw
  107. assert self.save is None
  108. assert self.keepalive is None
  109. # Note: This clears out the server "keep alive"
  110. self.save = self.observer.save()
  111. self.observer.connect("player", self.get_input)
  112. self.keepalive = task.LoopingCall(self.alive)
  113. self.keepalive.start(30)
  114. # We need to "hide" the game output.
  115. # Otherwise it WITH mess up the user input display.
  116. self.to_player = self.game.to_player
  117. self.game.to_player = False
  118. # Display prompt
  119. # self.queue_game.put(self.r + self.nl + self.c + user_prompt + " " + self.cp)
  120. self.queue_game.put(self.r + self.c + user_prompt + self.r + " " + self.cp)
  121. # Set "Background of prompt"
  122. self.queue_game.put(" " * limit + "\b" * limit)
  123. assert self.deferred is None
  124. d = defer.Deferred()
  125. self.deferred = d
  126. log.debug("Return deferred ...")
  127. return d
  128. def get_input(self, chunk):
  129. """ Data from player (in bytes) """
  130. chunk = chunk.decode("latin-1", "ignore")
  131. for ch in chunk:
  132. if ch == "\b":
  133. if len(self.input) > 0:
  134. self.queue_game.put(self.bsb)
  135. self.input = self.input[0:-1]
  136. else:
  137. self.queue_game.put("\a")
  138. elif ch == "\r":
  139. self.queue_game.put(self.r + self.nl)
  140. log.debug("Restore observer dispatch {0}".format(self.save))
  141. assert not self.save is None
  142. self.observer.load(self.save)
  143. self.save = None
  144. log.debug("Disable keepalive")
  145. self.keepalive.stop()
  146. self.keepalive = None
  147. line = self.input
  148. self.input = ""
  149. assert not self.deferred is None
  150. self.game.to_player = self.to_player
  151. # If they gave us the keyword name, save the value as that name
  152. if "name" in self.kw:
  153. self.keep[self.kw["name"]] = line
  154. if "abort_blank" in self.kw and self.kw["abort_blank"]:
  155. # Abort on blank input
  156. if line.strip() == "":
  157. # Yes, input is blank, abort.
  158. log.info("errback, abort_blank")
  159. reactor.callLater(
  160. 0, self.deferred.errback, Exception("abort_blank")
  161. )
  162. self.deferred = None
  163. return
  164. # Ok, use deferred.callback, or reactor.callLater?
  165. # self.deferred.callback(line)
  166. reactor.callLater(0, self.deferred.callback, line)
  167. self.deferred = None
  168. return
  169. elif ch.isprintable():
  170. # Printable, but is it acceptable?
  171. if "digits" in self.kw:
  172. if not ch.isdigit():
  173. self.queue_game.put("\a")
  174. continue
  175. if len(self.input) + 1 <= self.limit:
  176. self.input += ch
  177. self.queue_game.put(ch)
  178. else:
  179. self.queue_game.put("\a")
  180. def output(self, line):
  181. """ A default display of what they just input. """
  182. log.debug("PlayerInput.output({0})".format(line))
  183. self.game.queue_game.put(self.r + "[{0}]".format(line) + self.nl)
  184. return line
  185. import re
  186. # The CIMWarpReport -- is only needed if the json file gets damaged in some way.
  187. # or needs to be reset. The warps should automatically update themselves now.
  188. class CIMWarpReport(object):
  189. def __init__(self, game):
  190. self.game = game
  191. self.queue_game = game.queue_game
  192. self.queue_player = game.queue_player
  193. self.observer = game.observer
  194. # Yes, at this point we would activate
  195. self.prompt = game.buffer
  196. self.save = self.observer.save()
  197. # I actually don't want the player input, but I'll grab it anyway.
  198. self.observer.connect("player", self.player)
  199. self.observer.connect("prompt", self.game_prompt)
  200. self.observer.connect("game-line", self.game_line)
  201. # If we want it, it's here.
  202. self.defer = None
  203. self.to_player = self.game.to_player
  204. # Hide what's happening from the player
  205. self.game.to_player = False
  206. self.queue_player.put("^") # Activate CIM
  207. self.state = 1
  208. # self.warpdata = {}
  209. self.warpcycle = SpinningCursor()
  210. def game_prompt(self, prompt):
  211. if prompt == ": ":
  212. if self.state == 1:
  213. # Ok, then we're ready to request the port report
  214. self.warpcycle.reset()
  215. self.queue_player.put("I")
  216. self.state = 2
  217. elif self.state == 2:
  218. self.queue_player.put("Q")
  219. self.state = 3
  220. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  221. if self.state == 3:
  222. # Ok, time to exit
  223. # exit from this...
  224. self.game.to_player = self.to_player
  225. self.observer.load(self.save)
  226. self.save = None
  227. # self.game.warpdata = self.warpdata
  228. self.queue_game.put("\b \b\r\n")
  229. if not self.defer is None:
  230. self.defer.callback(self.game.gamedata.warps)
  231. self.defer = None
  232. def game_line(self, line):
  233. if line == "" or line == ": ":
  234. return
  235. if line == ": ENDINTERROG":
  236. return
  237. if line.startswith('Command [TL='):
  238. return
  239. # This should be the CIM Report Data -- parse it
  240. if self.warpcycle:
  241. if self.warpcycle.click():
  242. self.queue_game.put("\b" + self.warpcycle.cycle())
  243. work = line.strip()
  244. parts = re.split(r"(?<=\d)\s", work)
  245. parts = [int(x) for x in parts]
  246. sector = parts.pop(0)
  247. # tuples are nicer on memory, and the warpdata map isn't going to be changing.
  248. # self.warpdata[sector] = tuple(parts)
  249. self.game.gamedata.warp_to(sector, *parts)
  250. def __del__(self):
  251. log.debug("CIMWarpReport {0} RIP".format(self))
  252. def whenDone(self):
  253. self.defer = defer.Deferred()
  254. # Call this to chain something after we exit.
  255. return self.defer
  256. def player(self, chunk):
  257. """ Data from player (in bytes). """
  258. chunk = chunk.decode("latin-1", "ignore")
  259. key = chunk.upper()
  260. log.warn("CIMWarpReport.player({0}) : I AM stopping...".format(key))
  261. # Stop the keepalive if we are activating something else
  262. # or leaving...
  263. # self.keepalive.stop()
  264. self.queue_game.put("\b \b\r\n")
  265. if not self.defer is None:
  266. # We have something, so:
  267. self.game.to_player = self.to_player
  268. self.observer.load(self.save)
  269. self.save = None
  270. self.defer.errback(Exception("User Abort"))
  271. self.defer = None
  272. else:
  273. # Still "exit" out.
  274. self.game.to_player = self.to_player
  275. self.observer.load(self.save)
  276. # the CIMPortReport will still be needed.
  277. # We can't get fresh report data (that changes) any other way.
  278. class CIMPortReport(object):
  279. """ Parse data from CIM Port Report
  280. Example:
  281. from flexible import CIMPortReport
  282. report = CIMPortReport(self.game)
  283. d = report.whenDone()
  284. d.addCallback(self.port_report)
  285. d.addErrback(self.welcome_back)
  286. def port_report(self, portdata):
  287. self.portdata = portdata
  288. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  289. self.welcome_back()
  290. def welcome_back(self,*_):
  291. ... restore keep alive timers, etc.
  292. """
  293. def __init__(self, game):
  294. self.game = game
  295. self.queue_game = game.queue_game
  296. self.queue_player = game.queue_player
  297. self.observer = game.observer
  298. # Yes, at this point we would activate
  299. self.prompt = game.buffer
  300. self.save = self.observer.save()
  301. # I actually don't want the player input, but I'll grab it anyway.
  302. self.observer.connect("player", self.player)
  303. self.observer.connect("prompt", self.game_prompt)
  304. self.observer.connect("game-line", self.game_line)
  305. # If we want it, it's here.
  306. self.defer = None
  307. self.to_player = self.game.to_player
  308. log.debug("to_player (stored) {0}".format(self.to_player))
  309. # Hide what's happening from the player
  310. self.game.to_player = False
  311. self.queue_player.put("^") # Activate CIM
  312. self.state = 1
  313. # self.portdata = {}
  314. self.portcycle = SpinningCursor()
  315. def game_prompt(self, prompt):
  316. if prompt == ": ":
  317. if self.state == 1:
  318. # Ok, then we're ready to request the port report
  319. self.portcycle.reset()
  320. self.queue_player.put("R")
  321. self.state = 2
  322. elif self.state == 2:
  323. self.queue_player.put("Q")
  324. self.state = 3
  325. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  326. if self.state == 3:
  327. # Ok, time to exit
  328. # exit from this...
  329. self.game.to_player = self.to_player
  330. self.observer.load(self.save)
  331. self.save = None
  332. # self.game.portdata = self.portdata
  333. self.queue_game.put("\b \b\r\n")
  334. if not self.defer is None:
  335. self.defer.callback(self.game.gamedata.ports)
  336. self.defer = None
  337. def game_line(self, line: str):
  338. if line == "" or line == ": ":
  339. return
  340. if line == ": ENDINTERROG":
  341. return
  342. # This should be the CIM Report Data -- parse it
  343. if self.portcycle:
  344. if self.portcycle.click():
  345. self.queue_game.put("\b" + self.portcycle.cycle())
  346. work = line.replace("%", "")
  347. parts = re.split(r"(?<=\d)\s", work)
  348. if len(parts) == 8:
  349. port = int(parts[0].strip())
  350. data = dict()
  351. def portBS(info):
  352. if info[0] == "-":
  353. bs = "B"
  354. else:
  355. bs = "S"
  356. return (bs, int(info[1:].strip()))
  357. data["fuel"] = dict()
  358. data["fuel"]["sale"], data["fuel"]["units"] = portBS(parts[1])
  359. data["fuel"]["pct"] = int(parts[2].strip())
  360. data["org"] = dict()
  361. data["org"]["sale"], data["org"]["units"] = portBS(parts[3])
  362. data["org"]["pct"] = int(parts[4].strip())
  363. data["equ"] = dict()
  364. data["equ"]["sale"], data["equ"]["units"] = portBS(parts[5])
  365. data["equ"]["pct"] = int(parts[6].strip())
  366. # Store what this port is buying/selling
  367. data["port"] = (
  368. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  369. )
  370. # Convert BBS/SBB to Class number 1-8
  371. data["class"] = CLASSES_PORT[data["port"]]
  372. self.game.gamedata.set_port(port, data)
  373. # self.portdata[port] = data
  374. else:
  375. log.error("CIMPortReport: {0} ???".format(line))
  376. def __del__(self):
  377. log.debug("CIMPortReport {0} RIP".format(self))
  378. def whenDone(self):
  379. self.defer = defer.Deferred()
  380. # Call this to chain something after we exit.
  381. return self.defer
  382. def player(self, chunk):
  383. """ Data from player (in bytes). """
  384. chunk = chunk.decode("latin-1", "ignore")
  385. key = chunk.upper()
  386. log.warn("CIMPortReport.player({0}) : I AM stopping...".format(key))
  387. # Stop the keepalive if we are activating something else
  388. # or leaving...
  389. # self.keepalive.stop()
  390. self.queue_game.put("\b \b\r\n")
  391. if not self.defer is None:
  392. # We have something, so:
  393. self.game.to_player = self.to_player
  394. self.observer.load(self.save)
  395. self.save = None
  396. self.defer.errback(Exception("User Abort"))
  397. self.defer = None
  398. else:
  399. # Still "exit" out.
  400. self.game.to_player = self.to_player
  401. self.observer.load(self.save)
  402. class ScriptPort(object):
  403. """ Performs the Port script.
  404. This is close to the original.
  405. We don't ask for the port to trade with --
  406. because that information is available to us after "D" (display).
  407. We look at the adjacent sectors, and see if we know any ports.
  408. If the ports are burnt (< 20%), we remove them from the list.
  409. We sort the best trades first.
  410. If there's just one, we use it. Otherwise we ask them to choose.
  411. We have options Trade_UseFirst, which uses the first one, if
  412. there is more then one.
  413. Option Trade_Turns, will use this as default turns, without
  414. asking.
  415. """
  416. def __init__(self, game):
  417. self.game = game
  418. self.queue_game = game.queue_game
  419. self.queue_player = game.queue_player
  420. self.observer = game.observer
  421. self.r = Style.RESET_ALL
  422. self.nl = "\n\r"
  423. self.this_sector = None # Starting sector
  424. self.sector1 = None # Current Sector
  425. self.sector2 = None # Next Sector Stop
  426. self.percent = self.game.gamedata.get_config('Trade_Percent', '5')
  427. update_config = False
  428. try:
  429. self.percent = int(self.percent)
  430. except ValueError:
  431. self.percent = 5
  432. update_config = True
  433. if self.percent > 50:
  434. self.percent = 5
  435. update_config = True
  436. if self.percent < 0:
  437. self.percent = 0
  438. update_config = True
  439. if update_config:
  440. self.game.gamedata.set_config('Trade_Percent', self.percent)
  441. self.credits = 0
  442. self.last_credits = None
  443. self.times_left = 0
  444. # Activate
  445. self.prompt = game.buffer
  446. self.save = self.observer.save()
  447. self.observer.connect('player', self.player)
  448. self.observer.connect("prompt", self.game_prompt)
  449. self.observer.connect("game-line", self.game_line)
  450. self.defer = None
  451. self.send2player("Script based on: Port Pair Trading v2.00")
  452. self.possible_sectors = None
  453. self.state = 1
  454. self.queue_player.put("D")
  455. # Original, send 'D' to display current sector.
  456. # We could get the sector number from the self.prompt string -- HOWEVER:
  457. # IF! We send 'D', we can also get the sectors around -- we might not even need to
  458. # prompt for sector to trade with (we could possibly figure it out ourselves).
  459. # [Command [TL=00:00:00]:[967] (?=Help)? : D]
  460. # [<Re-Display>]
  461. # []
  462. # [Sector : 967 in uncharted space.]
  463. # [Planets : (M) Into the Darkness]
  464. # [Warps to Sector(s) : 397 - (562) - (639)]
  465. # []
  466. def whenDone(self):
  467. self.defer = defer.Deferred()
  468. # Call this to chain something after we exit.
  469. return self.defer
  470. def deactivate(self, andExit=True):
  471. self.state = 0
  472. log.debug("ScriptPort.deactivate ({0})".format(self.times_left))
  473. self.queue_game.put(self.nl + Boxes.alert("Trading Script deactivating..."))
  474. assert(not self.save is None)
  475. self.observer.load(self.save)
  476. self.save = None
  477. if self.defer:
  478. if andExit:
  479. self.defer.callback({'exit':True})
  480. else:
  481. self.defer.callback('done')
  482. self.defer = None
  483. def player(self, chunk: bytes):
  484. # If we receive anything -- ABORT!
  485. self.deactivate()
  486. def send2game(self, txt):
  487. log.debug("ScriptPort.send2game({0})".format(txt))
  488. self.queue_player.put(txt)
  489. def send2player(self, txt):
  490. log.debug("ScriptPort.send2player({0})".format(txt))
  491. self.queue_game.put(
  492. self.nl + txt + self.r + self.nl
  493. )
  494. def game_prompt(self, prompt: str):
  495. log.debug("{0} : {1}".format(self.state, prompt))
  496. if self.state == 3:
  497. # log.("game_prompt: ", prompt)
  498. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  499. self.state = 4
  500. log.debug("Ok, state 4")
  501. use_first = self.game.gamedata.get_config('Trade_UseFirst', 'N').upper()[0] == 'Y'
  502. if self.sector2 is None and use_first:
  503. # Use the first one by default
  504. self.sector2 = self.possible[0]
  505. log.info("default to {0}".format(self.sector2))
  506. if self.sector2 is None:
  507. # Ok, we need to prompt for this.
  508. self.queue_game.put(self.r + self.nl +
  509. "Which sector to trade with? {0}".format(GameData.port_show_part(self.this_sector, self.game.gamedata.ports[self.this_sector])) +
  510. self.nl)
  511. for i, p in enumerate(self.possible):
  512. self.queue_game.put(" " + Fore.CYAN + str(i + 1) + " : " + GameData.port_show_part(p, self.game.gamedata.ports[p]) + self.nl)
  513. pi = PlayerInput(self.game)
  514. def got_need1(*_):
  515. log.debug("Ok, I have: {0}".format(pi.keep))
  516. if pi.keep['count'].strip() == '':
  517. self.deactivate()
  518. return
  519. self.times_left = int(pi.keep['count'])
  520. if pi.keep['choice'].strip() == '':
  521. self.deactivate()
  522. return
  523. c = int(pi.keep['choice']) -1
  524. if c < 0 or c >= len(self.possible):
  525. self.deactivate()
  526. return
  527. self.sector2 = self.possible[int(pi.keep['choice']) -1]
  528. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  529. self.state = 5
  530. self.trade()
  531. d = pi.prompt("Choose -=>", 5, name='choice', digits=True)
  532. d.addCallback(lambda ignore: pi.prompt("Times to execute script:", 5, name='count', digits=True))
  533. d.addCallback(got_need1)
  534. else:
  535. # We already have our target port, so...
  536. self.queue_game.put(self.r + self.nl + "Trading from {0} ({1}) to default {2} ({3}).".format(
  537. self.this_sector,
  538. self.game.gamedata.ports[self.this_sector]['port'],
  539. self.sector2, self.game.gamedata.ports[self.sector2]['port']) + self.nl
  540. )
  541. self.queue_game.put(self.r + self.nl + "Trading {0}".format(
  542. self.game.gamedata.port_trade_show(self.this_sector,
  543. self.sector2, 0)
  544. ))
  545. pi = PlayerInput(self.game)
  546. def got_need2(*_):
  547. if pi.keep['count'].strip() == '':
  548. self.deactivate()
  549. return
  550. self.times_left = int(pi.keep['count'])
  551. log.debug("Ok, I have: {0}".format(pi.keep))
  552. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  553. self.state = 5
  554. self.trade()
  555. self.queue_game.put(self.r + self.nl)
  556. default_turns = self.game.gamedata.get_config('Trade_Turns', '0')
  557. if default_turns == '0':
  558. # No default given, ask.
  559. d = pi.prompt("Times to execute script", 5, name='count')
  560. d.addCallback(got_need2)
  561. else:
  562. try:
  563. self.times_left = int(default_turns)
  564. except ValueError:
  565. self.times_left = 30
  566. self.state = 5
  567. self.trade()
  568. elif self.state == 6:
  569. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  570. if self.fixable:
  571. # self.queue_game.put("Ok! Let's fix this by going to the other sector..." + self.nl)
  572. self.queue_game.put(self.nl + Boxes.alert("Ok, FINE. We'll trade with the other port.", base="green", style=0))
  573. log.debug("Fixing...")
  574. # Swap this and other sector
  575. self.this_sector, self.other_sector = (self.other_sector, self.this_sector)
  576. self.queue_player.put("{0}\r".format(self.sector2))
  577. self.state = 5
  578. self.trade()
  579. elif self.state == 7:
  580. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  581. # Done
  582. # Swap this and other sector
  583. self.this_sector, self.other_sector = (self.other_sector, self.this_sector)
  584. if self.this_sector == self.sector2:
  585. self.times_left -= 1
  586. if self.times_left <= 0:
  587. # Ok, exit out
  588. self.deactivate()
  589. return
  590. if self.last_credits is None:
  591. self.last_credits = self.credits
  592. else:
  593. if self.credits <= self.last_credits:
  594. log.warn("We don't seem to be making any money here...")
  595. self.queue_game.put(self.r + self.nl + "We don't seem to be making any money here. I'm stopping!" + self.nl)
  596. self.deactivate()
  597. return
  598. self.queue_player.put("{0}\r".format(self.this_sector))
  599. self.state = 10
  600. elif re.match(r'Your offer \[\d+\] \?', prompt):
  601. log.info("Your offer? [{0}]".format(self.fix_offer))
  602. if self.fix_offer:
  603. # Make real offer / WHAT?@?!
  604. work = prompt.replace(',', '')
  605. parts = re.split(r"\s+", work)
  606. amount = parts[2]
  607. # Ok, we have the amount, now to figure pct...
  608. if self.sell_percent > 100:
  609. self.sell_percent -= 1
  610. else:
  611. self.sell_percent += 1
  612. price = amount * self.sell_percent // 100
  613. log.debug("start: {0} % {1} price {2}".format(amount, self.sell_percent, price))
  614. if self.sell_percent > 100:
  615. self.sell_percent -= 1
  616. else:
  617. self.sell_percent += 1
  618. self.queue_player.put("{0}\r".format(price))
  619. # elif re.match(r"How many holds of .+ do you want to sell \[\d+\]\?", prompt):
  620. # log.info("Sell everything we can...")
  621. # this seems to screw up the sync of everything.
  622. # self.queue_player.put("\r")
  623. elif self.state == 8:
  624. # What are we trading
  625. # How many holds of Equipment do you want to buy [75]?
  626. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\?", prompt):
  627. parts = prompt.split()
  628. trade_type = parts[4]
  629. log.info("Buy {0} [{1} ~ {2}]".format(trade_type, self.tpc, self.opc))
  630. if trade_type == 'Fuel':
  631. if (self.tpc in (5,7)) and (self.opc in (2,3,4,8)):
  632. # Can buy equipment - fuel ore is worthless.
  633. self.queue_player.put("0\r")
  634. return
  635. if (self.tpc in(4,7)) and (self.opc in (1,3,5,8)):
  636. # Can buy organics - fuel ore is worthless.
  637. self.queue_player.put("0\r")
  638. return
  639. if (self.tpc in (4,7,3,5)) and (self.opc in (3,4,5,7)):
  640. # No point in buying fuel ore if it can't be sold.
  641. self.queue_player.put("0\r")
  642. return
  643. elif trade_type == 'Organics':
  644. if (self.tpc in (6,7)) and (self.opc in (2,3,4,8)):
  645. # Can buy equipment - organics is worthless.
  646. self.queue_player.put("0\r")
  647. return
  648. if (self.tpc in (2,4,6,7)) and (self.opc in (2,4,6,7)):
  649. # No point in buying organics if it can't be sold.
  650. self.queue_player.put("0\r")
  651. return
  652. elif trade_type == 'Equipment':
  653. if (self.opc in (1,5,6,7)):
  654. # No point in buying equipment if it can't be sold.
  655. self.queue_player.put("0\r")
  656. return
  657. self.queue_player.put("\r")
  658. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  659. # Done
  660. # Swap this and other sector
  661. self.this_sector, self.other_sector = (self.other_sector, self.this_sector)
  662. if self.this_sector == self.sector2:
  663. self.times_left -= 1
  664. if self.times_left <= 0:
  665. # Ok, exit out
  666. self.deactivate()
  667. return
  668. if self.last_credits is None:
  669. self.last_credits = self.credits
  670. else:
  671. if self.credits <= self.last_credits:
  672. log.warn("We don't seem to be making any money here...")
  673. self.queue_game.put(self.r + self.nl + "We don't seem to be making any money here. I'm stopping!" + self.nl)
  674. self.deactivate()
  675. return
  676. self.queue_player.put("{0}\r".format(self.this_sector))
  677. self.state = 10
  678. elif self.state == 99:
  679. # This is a good place to deactivate at.
  680. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  681. if hasattr(self, 'message'):
  682. if self.message is not None:
  683. self.queue_game.put(self.message)
  684. self.message = None
  685. self.deactivate()
  686. def trade(self, *_):
  687. # state 5
  688. log.debug("trade!")
  689. self.queue_player.put("pt") # Port Trade
  690. self.fixable = False
  691. self.this_port = self.game.gamedata.ports[self.this_sector]
  692. # I think other_sector will alway be correct, but leaving this
  693. # for now. FUTURE: TODO: REMOVE
  694. if self.this_sector == self.sector1:
  695. self.other_sector = self.sector2
  696. else:
  697. self.other_sector = self.sector1
  698. self.other_port = self.game.gamedata.ports[self.other_sector]
  699. # Ok, perform some calculations
  700. self.tpc = self.this_port['class']
  701. self.opc = self.other_port['class']
  702. self.fixable = 0
  703. self.fix_offer = 0
  704. # [ Items Status Trading % of max OnBoard]
  705. # [ ----- ------ ------- -------- -------]
  706. # [Fuel Ore Selling 2573 93% 0]
  707. # [Organics Buying 2960 100% 0]
  708. # [Equipment Buying 1958 86% 0]
  709. # []
  710. # []
  711. # [You have 1,000 credits and 20 empty cargo holds.]
  712. # []
  713. # [We are selling up to 2573. You have 0 in your holds.]
  714. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  715. def game_line(self, line: str):
  716. if line.startswith("You have ") and 'credits and' in line:
  717. parts = line.replace(',', '').split()
  718. credits = int(parts[2])
  719. log.debug("Credits: {0}".format(credits))
  720. self.credits = credits
  721. if self.state == 1:
  722. # First exploration
  723. if line.startswith("Sector :"):
  724. # We have starting sector information
  725. parts = re.split(r"\s+", line)
  726. self.this_sector = int(parts[2])
  727. # These will be the ones swapped around as we trade back and forth.
  728. self.sector1 = self.this_sector
  729. elif line.startswith("Warps to Sector(s) : "):
  730. # Warps to Sector(s) : 397 - (562) - (639)
  731. _, _, warps = line.partition(':')
  732. warps = warps.replace('-', '').replace('(', '').replace(')', '').strip()
  733. log.debug("Warps: [{0}]".format(warps))
  734. self.warps = [ int(x) for x in re.split(r"\s+", warps)]
  735. log.debug("Warps: [{0}]".format(self.warps))
  736. self.state = 2
  737. elif self.state == 2:
  738. if line == "":
  739. # Ok, we're done
  740. self.state = 3
  741. # Check to see if we have information on any possible ports
  742. # if hasattr(self.game, 'portdata'):
  743. if True:
  744. if not self.this_sector in self.game.gamedata.ports:
  745. self.state = 0
  746. log.debug("Current sector {0} not in portdata.".format(self.this_sector))
  747. self.queue_game.put(self.r + self.nl + "I can't find the current sector in the portdata." + self.nl)
  748. self.deactivate()
  749. return
  750. else:
  751. # Ok, we are in the portdata
  752. pd = self.game.gamedata.ports[self.this_sector]
  753. if GameData.port_burnt(pd):
  754. log.debug("Current sector {0} port is burnt (<= 20%).".format(self.this_sector))
  755. self.queue_game.put(self.r + self.nl + "Current sector port is burnt out. <= 20%." + self.nl)
  756. self.deactivate()
  757. return
  758. possible = [ x for x in self.warps if x in self.game.gamedata.ports ]
  759. log.debug("Possible: {0}".format(possible))
  760. # BUG: Sometimes links to another sector, don't link back!
  761. # This causes the game to plot a course / autopilot.
  762. # if hasattr(self.game, 'warpdata'):
  763. if True:
  764. # Great! verify that those warps link back to us!
  765. possible = [ x for x in possible if x in self.game.gamedata.warps and self.this_sector in self.game.gamedata.warps[x]]
  766. if len(possible) == 0:
  767. self.state = 0
  768. self.queue_game.put(self.r + self.nl + "I don't see any ports in [{0}].".format(self.warps) + self.nl)
  769. self.deactivate()
  770. return
  771. possible = [ x for x in possible if not GameData.port_burnt(self.game.gamedata.ports[x]) ]
  772. log.debug("Possible: {0}".format(possible))
  773. if len(possible) == 0:
  774. self.state = 0
  775. self.queue_game.put(self.r + self.nl + "I don't see any unburnt ports in [{0}].".format(self.warps) + self.nl)
  776. self.deactivate()
  777. return
  778. possible = [ x for x in possible if GameData.port_trading(self.game.gamedata.ports[self.this_sector]['port'], self.game.gamedata.ports[x]['port'])]
  779. # sort by best, then by %
  780. start_port = self.game.gamedata.ports[self.this_sector]
  781. if 'port' in start_port:
  782. start_port_port = start_port['port']
  783. start_with = start_port_port[1:]
  784. if start_with in ('BS', 'SB'):
  785. # Ok, good trades may be possible
  786. best = GameData.flip(start_with)
  787. log.info("Sorting the best ({0}) to the top.".format(best))
  788. log.info("{0}".format(possible))
  789. dec = [ [self.game.gamedata.ports[p].get('port', '---')[1:] == best, p] for p in possible]
  790. dec = sorted(dec, reverse=True)
  791. possible = [x[1] for x in dec]
  792. log.info("{0}".format(possible))
  793. self.possible = possible
  794. if len(possible) == 0:
  795. self.state = 0
  796. self.queue_game.put(self.r + self.nl + "I don't see any possible port trades in [{0}].".format(self.warps) + self.nl)
  797. self.deactivate()
  798. return
  799. elif len(possible) == 1:
  800. # Ok! there's only one!
  801. self.sector2 = possible[0]
  802. # Display possible ports:
  803. # spos = [ str(x) for x in possible]
  804. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  805. # At state 3, we only get a prompt.
  806. return
  807. else:
  808. self.state = 0
  809. log.warn("We don't have any portdata!")
  810. self.queue_game.put(self.r + self.nl + "I have no portdata. Please run CIM Port Report." + self.nl)
  811. self.deactivate()
  812. return
  813. elif self.state == 5:
  814. if "-----" in line:
  815. self.state = 6
  816. elif self.state == 6:
  817. if "We are buying up to" in line:
  818. log.info("buying up to -- so sell all")
  819. # Sell
  820. self.state = 7
  821. self.queue_player.put("\r")
  822. self.sell_percent = 100 + self.percent
  823. if "We are selling up to" in line:
  824. log.info("selling up to -- state 8 / set percent")
  825. # Buy
  826. self.state = 8
  827. self.sell_percent = 100 - self.percent
  828. if line.startswith('Fuel Ore') or line.startswith('Organics') or line.startswith('Equipment'):
  829. work = line.replace('Fuel Ore', 'Fuel')
  830. parts = re.split(r"\s+", work)
  831. # log.debug(parts)
  832. # Equipment, Selling xxx x% xxx
  833. if parts[-1] != '0' and parts[2] != '0' and parts[1] != 'Buying':
  834. log.warn("We have a problem -- they aren't buying what we have in stock!")
  835. stuff = line[0] # F O or E.
  836. if self.game.gamedata.port_buying(self.other_sector, stuff):
  837. log.info("fixable")
  838. self.fixable = True
  839. if "You don't have anything they want" in line:
  840. log.warn("Don't have anything they want.")
  841. # Neither! DRAT!
  842. if not self.fixable:
  843. self.state = 99
  844. return
  845. if "We're not interested." in line:
  846. log.warn("Try, try again. :(")
  847. self.state = 5
  848. self.trade()
  849. elif self.state == 7:
  850. # Haggle Sell
  851. if "We'll buy them for" in line or "Our final offer" in line:
  852. if "Our final offer" in line:
  853. self.sell_percent -= 1
  854. parts = line.replace(',', '').split()
  855. start_price = int(parts[4])
  856. price = start_price * self.sell_percent // 100
  857. log.debug("start: {0} % {1} price {2}".format(start_price, self.sell_percent, price))
  858. self.sell_percent -= 1
  859. self.queue_player.put("{0}\r".format(price))
  860. if "We are selling up to" in line:
  861. log.info("selling up to / state 8 / set percent")
  862. # Buy
  863. self.state = 8
  864. self.sell_percent = 100 - self.percent
  865. if "We are buying up to" in line:
  866. log.info("buying up to -- so sell all")
  867. # Sell
  868. self.state = 7
  869. self.queue_player.put("\r")
  870. self.sell_percent = 100 + self.percent
  871. if "We're not interested." in line:
  872. log.info("Not interested. Try, try again. :(")
  873. self.state = 5
  874. self.trade()
  875. if "WHAT?!@!? you must be crazy!" in line:
  876. log.warn("fix offer")
  877. self.fix_offer = 1
  878. if "So, you think I'm as stupid as you look?" in line:
  879. log.warn("fix offer")
  880. self.fix_offer = 1
  881. if "Quit playing around, you're wasting my time!" in line:
  882. log.warn("fix offer")
  883. self.fix_offer = 1
  884. elif self.state == 8:
  885. # Haggle Buy
  886. if "We'll sell them for" in line or "Our final offer" in line:
  887. if "Our final offer" in line:
  888. self.sell_percent += 1
  889. parts = line.replace(',', '').split()
  890. start_price = int(parts[4])
  891. price = start_price * self.sell_percent // 100
  892. log.debug("start: {0} % {1} price {2}".format(start_price, self.sell_percent, price))
  893. self.sell_percent += 1
  894. self.queue_player.put("{0}\r".format(price))
  895. if "We're not interested." in line:
  896. log.info("Not interested. Try, try again. :(")
  897. self.state = 5
  898. self.trade()
  899. elif self.state == 10:
  900. if "Sector : " in line:
  901. # Trade
  902. self.state = 5
  903. reactor.callLater(0, self.trade, 0)
  904. # self.trade()
  905. # elif self.state == 3:
  906. # log.debug("At state 3 [{0}]".format(line))
  907. # self.queue_game.put("At state 3.")
  908. # self.deactivate()
  909. # return
  910. class ScriptExplore(object):
  911. """ Script Explore v1.00
  912. By: David Thielemann
  913. WARNINGS:
  914. We assume the player has a Holo-Scanner!
  915. We assume the player has lots o turns, or unlimited turns!
  916. We assume the player is aware we run infinitely until we can't find new sectors to move to!
  917. """
  918. def __init__(self, game):
  919. self.game = game
  920. self.queue_game = game.queue_game
  921. self.queue_player = game.queue_player
  922. self.observer = game.observer
  923. self.r = Style.RESET_ALL
  924. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  925. self.nl = "\n\r"
  926. # Our Stuff, Not our pants!
  927. self.dense = [] # We did a density, store that info.
  928. self.clear = [] # Warps that we know are clear.
  929. self.highsector = 0 # Selected Sector to move to next!
  930. self.highwarp = 0 # Selected Sector's Warp Count!
  931. self.stacksector = [] # Set of sectors that we have not picked but are unexplored... even though we did a holo!
  932. self.oneMoveSector = False
  933. self.times = 0
  934. self.maxtimes = 0
  935. # Activate
  936. self.prompt = game.buffer
  937. self.save = self.observer.save()
  938. self.observer.connect('player', self.player)
  939. self.observer.connect("prompt", self.game_prompt)
  940. self.observer.connect("game-line", self.game_line)
  941. self.defer = None
  942. self.send2player(Boxes.alert("Explorer v1.01", base="green"))
  943. # How many times we going to go today?
  944. ask = PlayerInput(self.game)
  945. def settimes(*_):
  946. times = ask.keep['times'].strip()
  947. log.debug("settimes got '{0}'".format(times))
  948. if times == '':
  949. self.deactivate()
  950. else:
  951. times = int(times)
  952. self.times = times
  953. self.maxtimes = times
  954. self.send2game("D")
  955. log.debug("times: {0} maxtimes: {0}".format(self.times))
  956. self.state = 1
  957. d = ask.prompt("How many sectors would you like to explorer?", 5, name="times", digits=True)
  958. #d.addCallback(ask.output)
  959. #d.addCallback(lambda ignore: self.settimes(ask.keep))
  960. d.addCallback(settimes)
  961. def whenDone(self):
  962. self.defer = defer.Deferred()
  963. # Call this to chain something after we exit.
  964. return self.defer
  965. def deactivate(self, andExit=False):
  966. self.state = 0
  967. log.debug("ScriptExplore.deactivate()")
  968. assert(not self.save is None)
  969. self.observer.load(self.save)
  970. self.save = None
  971. if self.defer:
  972. if andExit:
  973. self.defer.callback({'exit':True})
  974. else:
  975. self.defer.callback('done')
  976. self.defer = None
  977. def player(self, chunk: bytes):
  978. # If we receive anything -- ABORT!
  979. self.deactivate(True)
  980. def send2game(self, txt):
  981. log.debug("ScriptExplore.send2game({0})".format(txt))
  982. self.queue_player.put(txt)
  983. def send2player(self, txt):
  984. log.debug("ScriptExplore.send2player({0})".format(txt))
  985. self.queue_game.put(
  986. self.nl + txt + self.r + self.nl
  987. )
  988. def resetStuff(self):
  989. self.dense = []
  990. self.clear = []
  991. self.highwarp = 0
  992. self.highsector = 0
  993. log.debug("ScriptExplore.resetStuff()")
  994. def dead_end(self):
  995. """ We've reached a dead end.
  996. Either pop a new location to travel to, or give it up.
  997. """
  998. self.send2player(Boxes.alert("** DEAD END **", base="blue"))
  999. if self.stacksector:
  1000. # Ok, there's somewhere to go ...
  1001. self.highsector = self.stacksector.pop()
  1002. # travel state
  1003. self.state = 10
  1004. self.send2game("{0}\r".format(self.highsector))
  1005. else:
  1006. self.send2player(Boxes.alert("I've run out of places to look ({0}/{1}).".format(self.maxtimes - self.times, self.maxtimes)))
  1007. self.deactivate(True)
  1008. def game_over(self, msg):
  1009. self.send2player(Boxes.alert("STOP: {0} ({1}/{2}).".format(msg, self.maxtimes - self.times, self.maxtimes)))
  1010. self.deactivate()
  1011. def game_prompt(self, prompt: str):
  1012. log.debug("{0} : {1}".format(self.state, prompt))
  1013. if self.state == 2:
  1014. if "Select (H)olo Scan or (D)ensity Scan or (Q)uit" in prompt:
  1015. self.send2game("D")
  1016. # self.state += 1
  1017. elif self.state == 5:
  1018. log.debug("dense is {0} sectors big".format(len(self.dense)))
  1019. self.state += 1
  1020. self.send2game("SH")
  1021. elif self.state == 10:
  1022. if prompt.startswith('Do you want to engage the TransWarp drive? '):
  1023. self.send2game("N")
  1024. elif self.state == 12:
  1025. # Looking for "Engage the Autopilot?"
  1026. if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
  1027. self.send2game("S")
  1028. self.travel_path.pop(0)
  1029. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
  1030. self.send2game("SD")
  1031. self.state += 1
  1032. # Arriving sector :1691 Autopilot disengaging.
  1033. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1034. log.info("We made it to where we wanted to go!")
  1035. # can't init state 1, because we're at a prompt, so...
  1036. self.send2game("S")
  1037. self.state = 2
  1038. return
  1039. elif self.state == 15:
  1040. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
  1041. self.send2game("N")
  1042. self.travel_path.pop(0)
  1043. self.state = 12
  1044. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1045. log.info("We made it to where we wanted to go!")
  1046. # can't init state 1, because we're at a prompt, so...
  1047. self.send2game("S")
  1048. self.state = 2
  1049. return
  1050. elif self.state == 20:
  1051. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
  1052. # Stop in this sector / Yes!
  1053. self.send2game("Y")
  1054. self.state = 1
  1055. # this should re-trigger a scan
  1056. def game_line(self, line: str):
  1057. log.debug("{0} | {1}".format(self.state, line))
  1058. #if "Mine Control" in line: # If we don't have a Holo-Scanner and we attempted to do a Holo-scan, abort
  1059. # self.deactivate()
  1060. if self.state == 1:
  1061. self.send2game("S")
  1062. self.state += 1
  1063. elif self.state == 2:
  1064. if "Relative Density Scan" in line:
  1065. self.state = 3
  1066. elif "You don't have a long range scanner." in line:
  1067. log.warn("FATAL: No Long Range Scanner Installed!")
  1068. self.send2player(Boxes.alert("You need a Long Range Scanner!"))
  1069. self.deactivate(True)
  1070. return
  1071. # elif "Long Range Scan" in line:
  1072. # self.state += 1
  1073. elif self.state == 3:
  1074. # Get the Density Data!
  1075. if line.startswith("Sector"):
  1076. new_sector = '(' in line
  1077. work = line.replace(':', '').replace(')', '').replace('(', '').replace('%', '').replace('==>', '')
  1078. work = re.split(r"\s+", work)
  1079. log.debug(work)
  1080. # 'Sector', '8192', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  1081. # 'Sector', '(', '8192)', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  1082. # New Sector?
  1083. if new_sector:
  1084. # Switch Anom into bool state
  1085. # if(work[8] == 'No'):
  1086. # temp = False
  1087. # else:
  1088. # temp = True
  1089. #self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': temp} )
  1090. self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': work[8] == 'Yes'} )
  1091. log.debug(self.dense)
  1092. # {'sector': 8192, 'density': 0, 'warps': 4, 'navhaz': 0, 'anom': False}
  1093. elif line == "":
  1094. self.state += 1
  1095. # yeah, this would be better in the above line...
  1096. # leaving it for now.
  1097. # Which is why I broke the elif chain. ...
  1098. if self.state == 4:
  1099. # Begin Processing our data we got from density scan and find highest warp count in what sectors
  1100. # Remove sectors with one warp
  1101. log.debug("state 4: {0}".format(self.dense))
  1102. # Do we have a new place to go? (That is also worth going to)
  1103. if not self.dense: # Dense contains no new sectors, abort
  1104. log.info("No New Sectors Found!")
  1105. self.dead_end()
  1106. return
  1107. # self.send2player(Boxes.alert("Find a new area for me to search in!"))
  1108. # Attempt to resolve no new sectors!
  1109. # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
  1110. # self.highsector = self.stacksector.pop()
  1111. # self.deactivate()
  1112. # elif self.dense: # Dense does contain at least 1 new sector, continue on
  1113. # ugh, actually, we don't care about making a list
  1114. # we only want to know if there's any that have warps > 1. :(
  1115. # see any:
  1116. # list comprehension
  1117. # t = [d for d in self.dense if d['warps'] > 1]
  1118. # t = [] # Pre-Test to check if there are just a bunch of 1 warp sectors
  1119. # for d in self.dense:
  1120. # if d['warps'] > 1:
  1121. # t.append(d['sector'])
  1122. # I don't care if there's only one warp. if it's un-explorered then
  1123. # explore it!
  1124. # if not any( w['warps'] > 1 for w in self.dense):
  1125. # # If there are no sectors with more that 1 warp, abort
  1126. # log.debug("No Sectors Found except one move sector!")
  1127. # self.dead_end()
  1128. # return
  1129. # self.send2player(Boxes.alert("Find a new area for me to look at!"))
  1130. # Attempt to resolve no new sectors with more than 1 warp!
  1131. # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
  1132. # self.highsector = self.stacksector.pop()
  1133. # self.deactivate()
  1134. # Is the sector safe to go into?
  1135. # self.clear = [ x['sector'] for x in self.dense if not x['anom'] and not x['navhaz'] and x['density'] in (0,1,100,101) and x['warps'] > 1 ]
  1136. self.clear = [ x for x in self.dense if not x['anom'] and not x['navhaz'] and x['density'] in (0,1,100,101) ]
  1137. # for d in self.dense:
  1138. # if not d['anom']:
  1139. # # Sector does not contain a Anomoly
  1140. # if not d['navhaz']:
  1141. # # Sector does not contain Hazards
  1142. # if d['density'] in (0, 1, 100, 101):
  1143. # # Sector does contain empty space / a beacon / a port / or a beacon and port
  1144. # if d['warps'] > 1:
  1145. # # If Sector is worth checking out?
  1146. # self.clear.append(d['sector'])
  1147. if self.clear: # We have sector(s) we can move to!
  1148. log.debug("Clear Sectors: {0}".format(len(self.clear)))
  1149. # This was state 5 but why can't we reduce number of states? ( Yeah let's kick California and New York out of the US, oh wrong states :P )
  1150. # Sort to find greatest warp count
  1151. self.highwarp, self.highsector = max( (x['warps'], x['sector']) for x in self.clear)
  1152. # for c in self.clear:
  1153. # for d in self.dense:
  1154. # if d['sector'] == c:
  1155. # if d['warps'] > self.highwarp:
  1156. # self.highwarp = d['warps']
  1157. # self.highsector = d['sector']
  1158. # elif d['warps'] == self.highwarp:
  1159. # if d['sector'] > self.highsector:
  1160. # self.highsector = d['sector']
  1161. # if self.highwarp and self.highsector:
  1162. log.info("Sector: {0:5d} Warps: {1}".format(self.highsector, self.highwarp))
  1163. self.state += 1
  1164. else:
  1165. log.warn("No (safe) sectors to move to!")
  1166. # Let's try this?!
  1167. # self.dead_end() # NO!
  1168. self.game_over("No SAFE moves.")
  1169. # Another NOP state. This also could be merged into above.
  1170. # break the elif chain.
  1171. if self.state == 5:
  1172. # Add the dense scan of unknown sectors onto the stack of sectors, only save the ones we think are clear... for now.
  1173. for c in self.clear:
  1174. sector = c['sector']
  1175. if sector != self.highsector:
  1176. if sector not in self.stacksector:
  1177. self.stacksector.append(sector)
  1178. # Or simply not add it in the first place ...
  1179. # Remove the sector we are just about to go to, we use discard so if the sector does not exist we don't throw a error!
  1180. # self.stacksector.discard(self.highsector)
  1181. # Ok, we need to decide to stop exploring -- before we
  1182. # issue the sector move! :P
  1183. #
  1184. # Warning! Yes we can and will eat all the turns! :P
  1185. if self.times == 0:
  1186. self.send2player(Boxes.alert("Completed {0}".format(self.maxtimes), base="green"))
  1187. log.info("Completed {0}".format(self.maxtimes))
  1188. self.deactivate()
  1189. return
  1190. self.times -= 1
  1191. # Ok we know the sector we want to go to now let's move it!
  1192. self.send2game("m{0}\r".format(self.highsector))
  1193. if self.highsector in self.stacksector:
  1194. log.info("Removing {0} from stacksector list.".format(self.highsector))
  1195. self.stacksector.remove(self.highsector)
  1196. # Reset Variables for fresh data
  1197. self.resetStuff()
  1198. self.state = 1
  1199. elif self.state == 10:
  1200. if line.startswith("You are already in that sector!"):
  1201. log.info("Already here. (Whoops!)")
  1202. self.state = 1
  1203. return
  1204. if line.startswith("Sector : {0}".format(self.highsector)):
  1205. log.info("We're here!")
  1206. # Ok, we're already there! no autopilot needed!
  1207. self.state = 1
  1208. return
  1209. # Warping
  1210. self.go_on = True
  1211. if line.startswith('The shortest path ('):
  1212. # Ok, we've got a path.
  1213. self.state += 1
  1214. self.travel_path = []
  1215. elif self.state == 11:
  1216. if line == '':
  1217. # The end of the (possibly) multiline warp.
  1218. self.state += 1
  1219. self.travel_path.pop(0) # First sector is one we're in.
  1220. self.stophere = False
  1221. self.go_on = True
  1222. else:
  1223. self.travel_path.extend(line.replace('(', '').replace(')', '').split(' > ') )
  1224. log.debug("Travel path: {0}".format(self.travel_path))
  1225. elif self.state == 12:
  1226. # Arriving sector :1691 Autopilot disengaging.
  1227. if 'Autopilot disengaging.' in line:
  1228. log.info("We made it to where we wanted to go!")
  1229. self.state = 1
  1230. return
  1231. elif self.state == 13:
  1232. if 'Relative Density Scan' in line:
  1233. self.state += 1
  1234. elif self.state == 14:
  1235. if line == "":
  1236. log.debug("PATH: {0}".format(self.travel_path))
  1237. # end of the scan, decision time
  1238. if self.stophere:
  1239. log.info("STOPHERE")
  1240. # Ok, let's stop here!
  1241. # Re-save the sector we were trying to get to. (we didn't make it there)
  1242. if self.highsector not in self.stacksector:
  1243. self.stacksector.append(self.highsector)
  1244. self.state = 20
  1245. else:
  1246. if self.go_on:
  1247. log.info("GO ON")
  1248. # Ok, carry on!
  1249. self.state = 15
  1250. else:
  1251. log.warn("Our way is blocked...")
  1252. if self.highsector not in self.stacksector:
  1253. self.stacksector.append(self.highsector)
  1254. self.state = 20
  1255. else:
  1256. if line.strip('-') != '':
  1257. work = line.replace(' :', '').replace('%', '').replace(')', '').replace('==>', '')
  1258. # Does this contain something new? unseen?
  1259. stophere = '(' in work
  1260. work = work.replace('(','')
  1261. #Sector XXXX DENS Warps N NavHaz P Anom YN
  1262. parts = re.split(r'\s+', work)
  1263. # Don't bother stopping if there's only one warp
  1264. # YES! Stop, even if there is just one warp!
  1265. # if stophere and parts[4] == '1':
  1266. # stophere = False
  1267. if stophere:
  1268. self.stophere = True
  1269. next_stop = self.travel_path[0]
  1270. log.debug("next_stop {0} from {1}".format(next_stop, self.travel_path))
  1271. log.debug("parts: {0}".format(parts))
  1272. if parts[1] == next_stop:
  1273. log.info("next_stop {0} found...".format(next_stop))
  1274. # Ok, this is our next stop. Is it safe to travel to?
  1275. if parts[2] not in ('100', '0', '1', '101'):
  1276. # Ok, it's not safe to go on.
  1277. self.go_on = False
  1278. # Check the rest navhav and anom ...
  1279. class ScriptSpace(object):
  1280. """ Space Exploration script.
  1281. Send "SD", verify paths are clear.
  1282. Find nearest unknown. Sector + CR.
  1283. Save "shortest path from to" information.
  1284. At 'Engage the Autopilot', Send "S" (Single Step)
  1285. At '[Stop in this sector', Send "SD", verify path is clear.
  1286. Send "SH" (glean sector/port information along the way.)
  1287. Send "N" (Next)!
  1288. Send "SD" / Verify clear.
  1289. Send "SH"
  1290. Repeat for Next closest.
  1291. """
  1292. def __init__(self, game):
  1293. self.game = game
  1294. self.queue_game = game.queue_game
  1295. self.queue_player = game.queue_player
  1296. self.observer = game.observer
  1297. self.r = Style.RESET_ALL
  1298. self.nl = "\n\r"
  1299. self.this_sector = None # Starting sector
  1300. self.target_sector = None # Sector going to
  1301. self.path = []
  1302. self.times_left = 0 # How many times to look for target
  1303. self.density = dict() # Results of density scan. (Just the numbers)
  1304. # Activate
  1305. self.prompt = game.buffer
  1306. self.save = self.observer.save()
  1307. self.observer.connect('player', self.player)
  1308. self.observer.connect("prompt", self.game_prompt)
  1309. self.observer.connect("game-line", self.game_line)
  1310. self.defer = None
  1311. self.queue_game.put(
  1312. self.nl + "Bugz (like space), is big." + self.r + self.nl
  1313. )
  1314. self.state = 1
  1315. self.queue_player.put("SD")
  1316. # Get current density scan + also get the current sector.
  1317. # [Command [TL=00:00:00]:[XXXX] (?=Help)? : D]
  1318. def whenDone(self):
  1319. self.defer = defer.Deferred()
  1320. # Call this to chain something after we exit.
  1321. return self.defer
  1322. def deactivate(self, andExit=False):
  1323. self.state = 0
  1324. log.debug("ScriptPort.deactivate ({0})".format(self.times_left))
  1325. assert(not self.save is None)
  1326. self.observer.load(self.save)
  1327. self.save = None
  1328. if self.defer:
  1329. if andExit:
  1330. self.defer.callback({'exit':True})
  1331. else:
  1332. self.defer.callback('done')
  1333. self.defer = None
  1334. def player(self, chunk: bytes):
  1335. # If we receive anything -- ABORT!
  1336. self.deactivate(True)
  1337. def unknown_search(self, starting_sector):
  1338. seen = set()
  1339. possible = set()
  1340. possible.add(int(starting_sector))
  1341. done = False
  1342. while not done:
  1343. next_possible = set()
  1344. for s in possible:
  1345. p = self.game.gamedata.get_warps(s)
  1346. if p is not None:
  1347. for pos in p:
  1348. if pos not in seen:
  1349. next_possible.add(pos)
  1350. else:
  1351. log.debug("unknown found: {0}".format(s))
  1352. self.unknown = s
  1353. done = True
  1354. break
  1355. seen.add(s)
  1356. if self.unknown is None:
  1357. log.debug("possible: {0}".format(next_possible))
  1358. possible = next_possible
  1359. yield
  1360. def find_unknown(self, starting_sector):
  1361. log.debug("find_unknown( {0})".format(starting_sector))
  1362. d = defer.Deferred()
  1363. # Process things
  1364. self.unknown = None
  1365. c = coiterate(self.unknown_search(starting_sector))
  1366. c.addCallback(lambda unknown: d.callback(self.unknown))
  1367. return d
  1368. def show_unknown(self, sector):
  1369. if sector is None:
  1370. self.deactivate()
  1371. return
  1372. log.debug("Travel to {0}...".format(sector))
  1373. self.queue_player.put("{0}\r".format(sector))
  1374. def game_prompt(self, prompt: str):
  1375. log.debug("{0} : {1}".format(self.state, prompt))
  1376. if self.state == 3:
  1377. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1378. # this_sector code isn't working -- so! Get sector from prompt
  1379. self.state = 4
  1380. _, _, sector = prompt.partition(']:[')
  1381. sector, _, _ = sector.partition(']')
  1382. self.this_sector = int(sector)
  1383. # Ok, we're done with Density Scan, and we're back at the command prompt
  1384. log.debug("Go find the nearest unknown...")
  1385. d = self.find_unknown(sector)
  1386. d.addCallback(self.show_unknown)
  1387. elif self.state == 6:
  1388. # Engage the autopilot?
  1389. if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
  1390. self.state = 7
  1391. sector = self.path.pop(0)
  1392. if sector in self.density:
  1393. if self.density[sector] in (0, 100):
  1394. # Ok, looks safe!
  1395. self.queue_player.put("S")
  1396. self.this_sector = sector
  1397. else:
  1398. log.warn("FATAL: Density for {0} is {1}".format(sector, self.density[sector]))
  1399. self.deactivate(True)
  1400. return
  1401. else:
  1402. log.error("{0} not in density scan? (how's that possible?)".format(sector))
  1403. self.deactivate(True)
  1404. return
  1405. elif self.state == 7:
  1406. # Ok, we're in a new sector (single stepping through space)
  1407. # update density scan
  1408. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1409. self.queue_player.put("SD")
  1410. self.state = 8
  1411. elif self.state == 10:
  1412. # Because we're here
  1413. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1414. self.queue_player.put("SH")
  1415. self.state = 11
  1416. elif self.state == 11:
  1417. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1418. # Ok, is the density scan clear?
  1419. sector = self.path.pop(0)
  1420. if sector in self.density:
  1421. if self.density[sector] in (0, 100):
  1422. # Ok, looks safe
  1423. self.queue_player.put("N")
  1424. self.state = 7
  1425. self.this_sector = sector
  1426. else:
  1427. log.warn("FATAL: Density for {0} is {1}".format(sector, self.density[sector]))
  1428. self.deactivate()
  1429. return
  1430. else:
  1431. log.error("{0} not in density scane? (how's that possible...)".format(sector))
  1432. self.deactivate()
  1433. return
  1434. def next_unknown(self, sector):
  1435. log.info("Unknown is : {0}".format(sector))
  1436. self.deactivate()
  1437. def game_line(self, line: str):
  1438. log.debug("line {0} : {1}".format(self.state, line))
  1439. if line.startswith('Sector : '):
  1440. work = line.strip()
  1441. parts = re.split(r"\s+", work)
  1442. self.this_sector = int(parts[2])
  1443. log.debug("game_line sector {0}".format(self.this_sector))
  1444. elif line.startswith("Command [TL=]"):
  1445. # Ok, get the current sector from this
  1446. _, _, sector = line.partition("]:[")
  1447. sector, _, _ = sector.partition("]")
  1448. self.this_sector = int(sector)
  1449. log.debug("current sector: {0}".format(self.this_sector))
  1450. elif line.startswith('Warps to Sector(s) :'):
  1451. # Warps to Sector(s) : 5468
  1452. _, _, work = line.partition(':')
  1453. work = work.strip().replace('(', '').replace(')', '').replace(' - ', ' ')
  1454. parts = [ int(x) for x in work.split(' ')]
  1455. self.path = list(parts)
  1456. if self.state in (1, 8):
  1457. if 'Relative Density Scan' in line:
  1458. # Start Density Scan
  1459. self.state += 1
  1460. self.density = {}
  1461. elif self.state in (2, 9):
  1462. if line == '':
  1463. # End of Density Scan
  1464. self.state += 1
  1465. log.debug("Density: {0}".format(self.density))
  1466. # self.deactivate()
  1467. elif line.startswith('Sector'):
  1468. # Parse Density Scan values
  1469. work = line.replace('(', '').replace(')', '').replace(':', '').replace('%', '').replace(',', '')
  1470. parts = re.split(r'\s+', work)
  1471. log.debug("Sector {0}".format(parts))
  1472. sector = int(parts[1])
  1473. self.density[sector] = int(parts[3])
  1474. if parts[7] != '0':
  1475. log.warn("NavHaz {0} : {1}".format(parts[7], work))
  1476. self.density[sector] += 99
  1477. if parts[9] != 'No':
  1478. log.warn("Anom {0} : {1}".format(parts[9], work))
  1479. self.density[sector] += 990
  1480. elif self.state == 4:
  1481. # Looking for shortest path message / warp info
  1482. # Or possibly, "We're here!"
  1483. if line.startswith('Sector :') and str(self.unknown) in line:
  1484. # Ok, I'd guess that we're already there!
  1485. # Try it again!
  1486. self.queue_player.put("SD")
  1487. self.state = 1
  1488. if line.startswith('The shortest path'):
  1489. self.state = 5
  1490. elif self.state == 5:
  1491. # This is the warps line
  1492. # Can this be multiple lines?
  1493. if line == "":
  1494. self.state = 6
  1495. else:
  1496. work = line.replace("(", "").replace(")", "").replace(">", "").strip()
  1497. self.path = [int(x) for x in work.split()]
  1498. log.debug("Path: {0}".format(self.path))
  1499. # Verify
  1500. current = self.path.pop(0)
  1501. if current != self.this_sector:
  1502. log.warn("Failed: {0} != {1}".format(current, self.this_sector))
  1503. self.deactivate()
  1504. return
  1505. elif self.state == 7:
  1506. if self.unknown == self.this_sector:
  1507. # We have arrived!
  1508. log.info("We're here!")
  1509. self.deactivate()
  1510. class ScriptTerror(object):
  1511. """ Terror script. """
  1512. def __init__(self, game, proxy, count):
  1513. self.game = game
  1514. self.queue_game = game.queue_game
  1515. self.queue_player = game.queue_player
  1516. self.proxy = proxy
  1517. self.count = count
  1518. self.observer = game.observer
  1519. self.r = Style.RESET_ALL
  1520. self.nl = "\n\r"
  1521. self.target_sector = self.proxy.find_next_good_trade_pair() # Sector going to
  1522. # Activate
  1523. self.prompt = game.buffer
  1524. self.save = self.observer.save()
  1525. self.observer.connect('player', self.player)
  1526. self.observer.connect("prompt", self.game_prompt)
  1527. self.observer.connect("game-line", self.game_line)
  1528. self.defer = None
  1529. self.state = 1
  1530. self.queue_player.put("{0}\r".format(self.target_sector))
  1531. def whenDone(self):
  1532. self.defer = defer.Deferred()
  1533. # Call this to chain something after we exit.
  1534. return self.defer
  1535. def deactivate(self, andExit=False):
  1536. self.state = 0
  1537. log.debug("ScriptTerror.deactivate")
  1538. assert(not self.save is None)
  1539. self.observer.load(self.save)
  1540. self.save = None
  1541. if self.defer:
  1542. if andExit:
  1543. self.defer.callback({'exit':True})
  1544. else:
  1545. self.defer.callback('done')
  1546. self.defer = None
  1547. def player(self, chunk: bytes):
  1548. # If we receive anything -- ABORT!
  1549. self.deactivate(True)
  1550. def journey_on(self, *_):
  1551. log.info("journey_on( {0})".format(self.count))
  1552. if self.count > 0:
  1553. self.count -= 1
  1554. self.target_sector = self.proxy.find_next_good_trade_pair() # Sector going to
  1555. self.state = 1
  1556. self.queue_player.put("{0}\r".format(self.target_sector))
  1557. else:
  1558. self.deactivate()
  1559. def game_prompt(self, prompt: str):
  1560. log.debug("{0} : {1}".format(self.state, prompt))
  1561. if self.state == 1:
  1562. if prompt.startswith('Do you want to engage the TransWarp drive? '):
  1563. self.queue_player.put("N")
  1564. elif self.state == 2:
  1565. if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
  1566. self.queue_player.put("E")
  1567. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1568. # We should be where we wanted to.
  1569. ports = ScriptPort(self.game)
  1570. d = ports.whenDone()
  1571. d.addCallback(self.journey_on)
  1572. d.addErrback(self.journey_on)
  1573. def game_line(self, line: str):
  1574. log.debug("line {0} : {1}".format(self.state, line))
  1575. if self.state == 1:
  1576. if line.startswith('The shortest path ('):
  1577. self.state = 2
  1578. class ProxyMenu(object):
  1579. """ Display ProxyMenu
  1580. Example:
  1581. from flexible import ProxyMenu
  1582. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1583. menu = ProxyMenu(self.game)
  1584. """
  1585. def __init__(self, game):
  1586. self.nl = "\n\r"
  1587. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  1588. self.r = Style.RESET_ALL
  1589. self.c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  1590. self.c2 = merge(Style.NORMAL + Fore.CYAN + Back.BLUE)
  1591. # self.portdata = None
  1592. self.game = game
  1593. self.queue_game = game.queue_game
  1594. self.observer = game.observer
  1595. # Am I using self or game? (I think I want game, not self.)
  1596. # if hasattr(self.game, "portdata"):
  1597. # self.portdata = self.game.portdata
  1598. # else:
  1599. # self.portdata = {}
  1600. # if hasattr(self.game, 'warpdata'):
  1601. # self.warpdata = self.game.warpdata
  1602. # else:
  1603. # self.warpdata = {}
  1604. if hasattr(self.game, 'trade_report'):
  1605. self.trade_report = self.game.trade_report
  1606. else:
  1607. self.trade_report = []
  1608. # Yes, at this point we would activate
  1609. self.prompt = game.buffer
  1610. self.save = self.observer.save()
  1611. self.observer.connect("player", self.player)
  1612. # If we want it, it's here.
  1613. self.defer = None
  1614. self.keepalive = task.LoopingCall(self.awake)
  1615. self.keepalive.start(30)
  1616. self.menu()
  1617. def __del__(self):
  1618. log.debug("ProxyMenu {0} RIP".format(self))
  1619. def whenDone(self):
  1620. self.defer = defer.Deferred()
  1621. # Call this to chain something after we exit.
  1622. return self.defer
  1623. def menu(self):
  1624. box = Boxes(30, color=self.c)
  1625. self.queue_game.put(box.top())
  1626. self.queue_game.put(
  1627. box.row(self.c + "{0:^30}".format("TradeWars Proxy Active")))
  1628. self.queue_game.put(box.middle())
  1629. def menu_item(ch: str, desc: str):
  1630. row = self.c1 + " {0} {1}- {2}{3:25}".format(ch, self.c2, self.c1, desc)
  1631. self.queue_game.put(box.row(row))
  1632. # self.queue_game.put(
  1633. # " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  1634. # )
  1635. menu_item("C", "Configuration ({0})".format(len(self.game.gamedata.config)))
  1636. menu_item("D", "Display Report again")
  1637. # menu_item("Q", "Quest")
  1638. menu_item("P", "Port CIM Report ({0})".format(len(self.game.gamedata.ports)))
  1639. menu_item("W", "Warp CIM Report ({0})".format(len(self.game.gamedata.warps)))
  1640. menu_item("T", "Trading Report")
  1641. menu_item("S", "Scripts")
  1642. menu_item("X", "eXit")
  1643. self.queue_game.put(box.bottom())
  1644. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  1645. def awake(self):
  1646. log.info("ProxyMenu.awake()")
  1647. self.game.queue_player.put(" ")
  1648. def port_report(self, portdata: dict):
  1649. # self.portdata = portdata
  1650. # self.game.portdata = portdata
  1651. self.queue_game.put("Loaded {0} ports.".format(len(portdata)) + self.nl)
  1652. self.welcome_back()
  1653. def warp_report(self, warpdata: dict):
  1654. # self.warpdata = warpdata
  1655. # self.game.warpdata = warpdata
  1656. self.queue_game.put("Loaded {0} sectors.".format(len(warpdata)) + self.nl)
  1657. self.welcome_back()
  1658. def find_next_good_trade_pair(self):
  1659. """ Find the next GOOD trade pair sector. """
  1660. show_limit = 90
  1661. for sector in sorted(self.game.gamedata.ports.keys()):
  1662. pd = self.game.gamedata.ports[sector]
  1663. if not GameData.port_burnt(pd):
  1664. pc = pd['class']
  1665. # Ok, let's look into it.
  1666. if not sector in self.game.gamedata.warps:
  1667. continue
  1668. warps = self.game.gamedata.warps[sector]
  1669. for w in warps:
  1670. # We can get there, and get back.
  1671. if w in self.game.gamedata.warps and sector in self.game.gamedata.warps[w]:
  1672. # Ok, we can get there -- and get back!
  1673. if w > sector and w in self.game.gamedata.ports and not GameData.port_burnt(self.game.gamedata.ports[w]):
  1674. wd = self.game.gamedata.ports[w]
  1675. wc = wd['class']
  1676. if pc in (1,5) and wc in (2,4):
  1677. data = self.game.gamedata.port_trade_show(sector, w, show_limit)
  1678. if data:
  1679. return sector
  1680. elif pc in (2,4) and wc in (1,5):
  1681. data = self.game.gamedata.port_trade_show(sector, w, show_limit)
  1682. if data:
  1683. return sector
  1684. # yield
  1685. return None
  1686. def make_trade_report(self):
  1687. log.debug("make_trade_report()")
  1688. ok_trades = []
  1689. best_trades = []
  1690. show_best = self.game.gamedata.get_config('Display_Best', 'Y').upper()[0] == 'Y'
  1691. show_ok = self.game.gamedata.get_config('Display_Ok', 'N').upper()[0] == 'Y'
  1692. show_limit = self.game.gamedata.get_config('Display_Percent', '90')
  1693. update_config = False
  1694. try:
  1695. show_limit = int(show_limit)
  1696. except ValueError:
  1697. show_limit = 90
  1698. update_config = True
  1699. if show_limit < 0:
  1700. show_limit = 0
  1701. update_config = True
  1702. elif show_limit > 100:
  1703. show_limit = 100
  1704. update_config = True
  1705. if update_config:
  1706. self.game.gamedata.set_config('Display_Percent', show_limit)
  1707. # for sector, pd in self.game.gamedata.ports.items():
  1708. for sector in sorted(self.game.gamedata.ports.keys()):
  1709. pd = self.game.gamedata.ports[sector]
  1710. if not GameData.port_burnt(pd):
  1711. pc = pd['class']
  1712. # Ok, let's look into it.
  1713. if not sector in self.game.gamedata.warps:
  1714. continue
  1715. warps = self.game.gamedata.warps[sector]
  1716. for w in warps:
  1717. # Verify that we have that warp's info, and that the sector is in it.
  1718. # (We can get back from it)
  1719. if w in self.game.gamedata.warps and sector in self.game.gamedata.warps[w]:
  1720. # Ok, we can get there -- and get back!
  1721. if w > sector and w in self.game.gamedata.ports and not GameData.port_burnt(self.game.gamedata.ports[w]):
  1722. # it is > and has a port.
  1723. wd = self.game.gamedata.ports[w]
  1724. wc = wd['class']
  1725. # 1: "BBS",
  1726. # 2: "BSB",
  1727. # 3: "SBB",
  1728. # 4: "SSB",
  1729. # 5: "SBS",
  1730. # 6: "BSS",
  1731. # 7: "SSS",
  1732. # 8: "BBB",
  1733. if pc in (1,5) and wc in (2,4):
  1734. data = self.game.gamedata.port_trade_show(sector, w, show_limit)
  1735. if data:
  1736. best_trades.append(data)
  1737. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  1738. elif pc in (2,4) and wc in (1,5):
  1739. data = self.game.gamedata.port_trade_show(sector, w, show_limit)
  1740. if data:
  1741. best_trades.append(data)
  1742. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  1743. elif GameData.port_trading(pd['port'], self.game.gamedata.ports[w]['port']):
  1744. # ok_trades.append( "{0:5} -=- {1:5}".format(sector,w))
  1745. data = self.game.gamedata.port_trade_show(sector, w, show_limit)
  1746. if data:
  1747. ok_trades.append(data)
  1748. yield
  1749. if show_best:
  1750. self.trade_report.append("Best Trades: (org/equ)")
  1751. self.trade_report.extend(best_trades)
  1752. if show_ok:
  1753. self.trade_report.append("Ok Trades:")
  1754. self.trade_report.extend(ok_trades)
  1755. if not show_best and not show_ok:
  1756. self.queue_game.put(Boxes.alert("You probably want to choose something to display in configuration!", base="red"))
  1757. # self.queue_game.put("BEST TRADES:" + self.nl + self.nl.join(best_trades) + self.nl)
  1758. # self.queue_game.put("OK TRADES:" + self.nl + self.nl.join(ok_trades) + self.nl)
  1759. def get_display_maxlines(self):
  1760. show_maxlines = self.game.gamedata.get_config('Display_Maxlines', '0')
  1761. try:
  1762. show_maxlines = int(show_maxlines)
  1763. except ValueError:
  1764. show_maxlines = 0
  1765. if show_maxlines <= 0:
  1766. show_maxlines = None
  1767. return show_maxlines
  1768. def show_trade_report(self, *_):
  1769. show_maxlines = self.get_display_maxlines()
  1770. self.game.trade_report = self.trade_report
  1771. for t in self.trade_report[:show_maxlines]:
  1772. self.queue_game.put(t + self.nl)
  1773. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  1774. self.observer.load(self.save)
  1775. self.save = None
  1776. self.keepalive = None
  1777. self.prompt = None
  1778. # self.welcome_back()
  1779. def player(self, chunk: bytes):
  1780. """ Data from player (in bytes). """
  1781. chunk = chunk.decode("latin-1", "ignore")
  1782. key = chunk.upper()
  1783. log.debug("ProxyMenu.player({0})".format(key))
  1784. # Stop the keepalive if we are activating something else
  1785. # or leaving...
  1786. self.keepalive.stop()
  1787. if key == "T":
  1788. self.queue_game.put(self.c + key + self.r + self.nl)
  1789. # Trade Report
  1790. # do we have enough information to do this?
  1791. # if not hasattr(self.game, 'portdata') and not hasattr(self.game, 'warpdata'):
  1792. # self.queue_game.put("Missing portdata and warpdata." + self.nl)
  1793. # elif not hasattr(self.game, 'portdata'):
  1794. # self.queue_game.put("Missing portdata." + self.nl)
  1795. # elif not hasattr(self.game, 'warpdata'):
  1796. # self.queue_game.put("Missing warpdata." + self.nl)
  1797. # else:
  1798. if True:
  1799. # Yes, so let's start!
  1800. self.trade_report = []
  1801. d = coiterate(self.make_trade_report())
  1802. d.addCallback(self.show_trade_report)
  1803. return
  1804. elif key == "P":
  1805. self.queue_game.put(self.c + key + self.r + self.nl)
  1806. self.game.gamedata.reset_ports()
  1807. # Activate CIM Port Report
  1808. report = CIMPortReport(self.game)
  1809. d = report.whenDone()
  1810. d.addCallback(self.port_report)
  1811. d.addErrback(self.welcome_back)
  1812. return
  1813. elif key == "W":
  1814. self.queue_game.put(self.c + key + self.r + self.nl)
  1815. self.game.gamedata.reset_warps()
  1816. # Activate CIM Warp Report
  1817. report = CIMWarpReport(self.game)
  1818. d = report.whenDone()
  1819. d.addCallback(self.warp_report)
  1820. d.addErrback(self.welcome_back)
  1821. return
  1822. elif key == "S":
  1823. self.queue_game.put(self.c + key + self.r + self.nl)
  1824. # Scripts
  1825. self.activate_scripts_menu()
  1826. return
  1827. elif key == "D":
  1828. self.queue_game.put(self.c + key + self.r + self.nl)
  1829. # (Re) Display Trade Report
  1830. show_maxlines = self.get_display_maxlines()
  1831. if self.trade_report:
  1832. for t in self.trade_report[:show_maxlines]:
  1833. self.queue_game.put(t + self.nl)
  1834. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  1835. self.observer.load(self.save)
  1836. self.save = None
  1837. self.keepalive = None
  1838. self.prompt = None
  1839. return
  1840. else:
  1841. self.queue_game.put("Missing trade_report." + self.nl)
  1842. elif key == "C":
  1843. self.queue_game.put(self.c + key + self.r + self.nl)
  1844. self.activate_config_menu()
  1845. return
  1846. # self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  1847. # self.queue_game.put(pformat(self.warpdata).replace("\n", "\n\r") + self.nl)
  1848. elif key == "Q":
  1849. self.queue_game.put(self.c + key + self.r + self.nl)
  1850. # This is an example of chaining PlayerInput prompt calls.
  1851. ask = PlayerInput(self.game)
  1852. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  1853. # Display the user's input
  1854. d.addCallback(ask.output)
  1855. d.addCallback(
  1856. lambda ignore: ask.prompt(
  1857. "What is your favorite color?", 10, name="color"
  1858. )
  1859. )
  1860. d.addCallback(ask.output)
  1861. d.addCallback(
  1862. lambda ignore: ask.prompt(
  1863. "What is the meaning of the squirrel?",
  1864. 12,
  1865. name="squirrel",
  1866. digits=True,
  1867. )
  1868. )
  1869. d.addCallback(ask.output)
  1870. def show_values(show):
  1871. log.debug(show)
  1872. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  1873. d.addCallback(lambda ignore: show_values(ask.keep))
  1874. d.addCallback(self.welcome_back)
  1875. # On error, just return back
  1876. # This doesn't seem to be getting called.
  1877. # d.addErrback(lambda ignore: self.welcome_back)
  1878. d.addErrback(self.welcome_back)
  1879. return
  1880. elif key == "X":
  1881. self.queue_game.put(self.c + key + self.r + self.nl)
  1882. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  1883. self.observer.load(self.save)
  1884. self.save = None
  1885. # It isn't running (NOW), so don't try to stop it.
  1886. # self.keepalive.stop()
  1887. self.keepalive = None
  1888. # Ok, this is a HORRIBLE idea, because the prompt might be
  1889. # outdated.
  1890. # self.queue_game.put(self.prompt)
  1891. self.prompt = None
  1892. # Send '\r' to re-display the prompt
  1893. # instead of displaying the original one.
  1894. self.game.queue_player.put("d")
  1895. # Were we asked to do something when we were done here?
  1896. if self.defer:
  1897. reactor.CallLater(0, self.defer.callback)
  1898. # self.defer.callback()
  1899. self.defer = None
  1900. return
  1901. self.keepalive.start(30, True)
  1902. self.menu()
  1903. def activate_config_menu(self):
  1904. self.observer.disconnect("player", self.player)
  1905. self.observer.connect("player", self.config_player)
  1906. self.config_menu()
  1907. def deactivate_config_menu(self, *data):
  1908. log.warn("deactivate_config_menu ({0})".format(data))
  1909. self.observer.disconnect("player", self.config_player)
  1910. self.observer.connect("player", self.player)
  1911. self.welcome_back()
  1912. def activate_scripts_menu(self):
  1913. self.observer.disconnect("player", self.player)
  1914. self.observer.connect("player", self.scripts_player)
  1915. self.scripts_menu()
  1916. def option_entry(self, entry):
  1917. if len(entry) > 0:
  1918. # Ok, they gave us something
  1919. self.game.gamedata.set_config(self.option_select, entry.strip())
  1920. else:
  1921. self.queue_game.put("Edit aborted." + self.nl)
  1922. self.config_menu()
  1923. def option_input(self, option):
  1924. if len(option) > 0:
  1925. option = int(option)
  1926. if option in self.config_opt:
  1927. # Ok, it's a valid option!
  1928. self.option_select = self.config_opt[option]
  1929. ask = PlayerInput(self.game)
  1930. d = ask.prompt("Change {0} to?".format(self.option_select), 18)
  1931. d.addCallback(self.option_entry)
  1932. # d.addErrback(self.config_menu)
  1933. else:
  1934. self.queue_game.put("Unknown option, sorry." + self.nl)
  1935. self.config_menu()
  1936. else:
  1937. # Aborted
  1938. self.config_menu()
  1939. def config_player(self, chunk: bytes):
  1940. """ Data from player (in bytes). """
  1941. chunk = chunk.decode("latin-1", "ignore")
  1942. key = chunk.upper()
  1943. if key == 'C':
  1944. self.queue_game.put(self.c + key + self.r + self.nl)
  1945. self.game.gamedata.config = {}
  1946. elif key == 'E':
  1947. self.queue_game.put(self.c + key + self.r + self.nl)
  1948. ask = PlayerInput(self.game)
  1949. d = ask.prompt("Which to edit?", 4, name='option', abort_blank=True, digits=True)
  1950. d.addCallback(self.option_input)
  1951. d.addErrback(self.config_menu)
  1952. return
  1953. elif key == 'X':
  1954. self.queue_game.put(self.c + key + self.r + self.nl)
  1955. self.deactivate_config_menu()
  1956. return
  1957. else:
  1958. self.queue_game.put(self.c + "?" + self.r + self.nl)
  1959. self.config_menu()
  1960. def config_menu(self, *_):
  1961. titlecolor = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  1962. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  1963. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  1964. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  1965. #box = Boxes(44, color=titlecolor)
  1966. box = Boxes(44, color=tc)
  1967. self.queue_game.put(box.top())
  1968. #self.queue_game.put(box.row(titlecolor + "{0:^44}".format("Configuration")))
  1969. self.queue_game.put(box.row(tc + "{0:^44}".format("Configuration")))
  1970. self.queue_game.put(box.middle())
  1971. def config_option(index, key, value):
  1972. row = "{0}{1:2} {2:19}{3}{4:<20}".format(c1, index, key, c2, value)
  1973. self.queue_game.put(box.row(row))
  1974. def menu_item(ch, desc):
  1975. row = "{0} {1} {2}-{3} {4:39}".format(c1, ch, c2, c1, desc)
  1976. # self.queue_game.put(
  1977. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  1978. # )
  1979. self.queue_game.put(box.row(row))
  1980. index = 1
  1981. self.config_opt = {}
  1982. for k in sorted(self.game.gamedata.config.keys()):
  1983. # for k, v in self.game.gamedata.config.items():
  1984. v = self.game.gamedata.config[k]
  1985. self.config_opt[index] = k
  1986. config_option(index, k, v)
  1987. index += 1
  1988. self.queue_game.put(box.middle())
  1989. menu_item("C", "Clear Config")
  1990. menu_item("E", "Edit Item")
  1991. menu_item("X", "eXit")
  1992. self.queue_game.put(box.bottom())
  1993. self.queue_game.put(" " + tc + "-=>" + self.r + " ")
  1994. def deactivate_scripts_menu(self, *data):
  1995. log.warn("deactivate_scripts_menu ({0})".format(data))
  1996. self.observer.disconnect("player", self.scripts_player)
  1997. self.observer.connect("player", self.player)
  1998. # Did they request exit?
  1999. if len(data) > 0 and type(data[0]) == dict:
  2000. info = data[0]
  2001. if 'exit' in info and info['exit']:
  2002. log.warn("exit proxy...")
  2003. # Exit Proxy Code
  2004. self.queue_game.put(Boxes.alert("Proxy done.", base="green",style=3))
  2005. self.observer.load(self.save)
  2006. self.save = None
  2007. # It isn't running (NOW), so don't try to stop it.
  2008. # self.keepalive.stop()
  2009. self.keepalive = None
  2010. # Ok, this is a HORRIBLE idea, because the prompt might be
  2011. # outdated.
  2012. # self.queue_game.put(self.prompt)
  2013. self.prompt = None
  2014. # I'm not sure where we are, we might not be at a prompt.
  2015. # let's check!
  2016. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", self.game.getPrompt()):
  2017. # Send '\r' to re-display the prompt
  2018. # instead of displaying the original one.
  2019. self.game.queue_player.put("d")
  2020. # Were we asked to do something when we were done here?
  2021. if self.defer:
  2022. reactor.CallLater(0, self.defer.callback)
  2023. # self.defer.callback()
  2024. self.defer = None
  2025. return
  2026. log.warn("calling welcome_back")
  2027. self.welcome_back()
  2028. def scripts_menu(self, *_):
  2029. c1 = merge(Style.BRIGHT + Fore.CYAN)
  2030. c2 = merge(Style.NORMAL + Fore.CYAN)
  2031. box = Boxes(40, color=c1)
  2032. self.queue_game.put(box.top())
  2033. self.queue_game.put(box.row(c1 + "{0:^40}".format("Scripts")))
  2034. self.queue_game.put(box.middle())
  2035. def menu_item(ch, desc):
  2036. row = " {0}{1} {2}-{3} {4:35}".format(c1, ch, c2, c1, desc)
  2037. # self.queue_game.put(
  2038. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  2039. # )
  2040. self.queue_game.put(box.row(row))
  2041. menu_item("1", "Ports (Trades between two sectors)")
  2042. menu_item("2", "Explore (Strange new sectors)")
  2043. menu_item("3", "Space... the final frontier...")
  2044. menu_item("X", "eXit")
  2045. self.queue_game.put(box.bottom())
  2046. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  2047. def terror(self, *_):
  2048. log.debug("terror {0}".format(_))
  2049. loops = _[0]
  2050. if loops.strip() == '':
  2051. self.deactivate_scripts_menu()
  2052. else:
  2053. # Ok, we have something here, I think...
  2054. terror = ScriptTerror(self.game, self, int(loops))
  2055. d = terror.whenDone()
  2056. d.addCallback(self.deactivate_scripts_menu)
  2057. d.addErrback(self.deactivate_scripts_menu)
  2058. def scripts_player(self, chunk: bytes):
  2059. """ Data from player (in bytes). """
  2060. chunk = chunk.decode("latin-1", "ignore")
  2061. key = chunk.upper()
  2062. if key == '1':
  2063. self.queue_game.put(self.c + key + self.r + self.nl)
  2064. # Activate this magical event here
  2065. ports = ScriptPort(self.game)
  2066. d = ports.whenDone()
  2067. # d.addCallback(self.scripts_menu)
  2068. # d.addErrback(self.scripts_menu)
  2069. d.addCallback(self.deactivate_scripts_menu)
  2070. d.addErrback(self.deactivate_scripts_menu)
  2071. return
  2072. elif key == '!':
  2073. self.queue_game.put(self.c + key + self.r + self.nl)
  2074. ask = PlayerInput(self.game)
  2075. d = ask.prompt("How many loops of terror?", 4, name="loops", digits=True, abort_blank=True)
  2076. d.addCallback(self.terror, ask)
  2077. return
  2078. elif key == '2':
  2079. self.queue_game.put(self.c + key + self.r + self.nl)
  2080. explore = ScriptExplore(self.game)
  2081. d = explore.whenDone()
  2082. d.addCallback(self.deactivate_scripts_menu)
  2083. d.addErrback(self.deactivate_scripts_menu)
  2084. return
  2085. elif key == '3':
  2086. self.queue_game.put(self.c + key + self.r + self.nl)
  2087. space = ScriptSpace(self.game)
  2088. d = space.whenDone()
  2089. d.addCallback(self.deactivate_scripts_menu)
  2090. d.addErrback(self.deactivate_scripts_menu)
  2091. return
  2092. elif key == 'X':
  2093. self.queue_game.put(self.c + key + self.r + self.nl)
  2094. self.deactivate_scripts_menu()
  2095. return
  2096. else:
  2097. self.queue_game.put(self.c + "?" + self.r + self.nl)
  2098. self.scripts_menu()
  2099. def welcome_back(self, *_):
  2100. log.debug("welcome_back")
  2101. self.keepalive.start(30, True)
  2102. self.menu()