flexible.py 98 KB

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