flexible.py 99 KB

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