flexible.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  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 consts
  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 ...", self.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", 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)", self.to_player)
  309. # Hide what's happening from the player
  310. self.game.to_player = False
  311. self.queue_player.put("^") # Activate CIM
  312. self.state = 1
  313. # self.portdata = {}
  314. self.portcycle = SpinningCursor()
  315. def game_prompt(self, prompt):
  316. if prompt == ": ":
  317. if self.state == 1:
  318. # Ok, then we're ready to request the port report
  319. self.portcycle.reset()
  320. self.queue_player.put("R")
  321. self.state = 2
  322. elif self.state == 2:
  323. self.queue_player.put("Q")
  324. self.state = 3
  325. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  326. if self.state == 3:
  327. # Ok, time to exit
  328. # exit from this...
  329. self.game.to_player = self.to_player
  330. self.observer.load(self.save)
  331. self.save = None
  332. # self.game.portdata = self.portdata
  333. self.queue_game.put("\b \b\r\n")
  334. if not self.defer is None:
  335. self.defer.callback(self.game.gamedata.ports)
  336. self.defer = None
  337. def game_line(self, line: str):
  338. if line == "" or line == ": ":
  339. return
  340. if line == ": ENDINTERROG":
  341. return
  342. # This should be the CIM Report Data -- parse it
  343. if self.portcycle:
  344. if self.portcycle.click():
  345. self.queue_game.put("\b" + self.portcycle.cycle())
  346. work = line.replace("%", "")
  347. parts = re.split(r"(?<=\d)\s", work)
  348. if len(parts) == 8:
  349. port = int(parts[0].strip())
  350. data = dict()
  351. def portBS(info):
  352. if info[0] == "-":
  353. bs = "B"
  354. else:
  355. bs = "S"
  356. return (bs, int(info[1:].strip()))
  357. data["fuel"] = dict()
  358. data["fuel"]["sale"], data["fuel"]["units"] = portBS(parts[1])
  359. data["fuel"]["pct"] = int(parts[2].strip())
  360. data["org"] = dict()
  361. data["org"]["sale"], data["org"]["units"] = portBS(parts[3])
  362. data["org"]["pct"] = int(parts[4].strip())
  363. data["equ"] = dict()
  364. data["equ"]["sale"], data["equ"]["units"] = portBS(parts[5])
  365. data["equ"]["pct"] = int(parts[6].strip())
  366. # Store what this port is buying/selling
  367. data["port"] = (
  368. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  369. )
  370. # Convert BBS/SBB to Class number 1-8
  371. data["class"] = CLASSES_PORT[data["port"]]
  372. self.game.gamedata.set_port(port, data)
  373. # self.portdata[port] = data
  374. else:
  375. log.error("CIMPortReport:", line, "???")
  376. def __del__(self):
  377. log.debug("CIMPortReport {0} RIP".format(self))
  378. def whenDone(self):
  379. self.defer = defer.Deferred()
  380. # Call this to chain something after we exit.
  381. return self.defer
  382. def player(self, chunk):
  383. """ Data from player (in bytes). """
  384. chunk = chunk.decode("latin-1", "ignore")
  385. key = chunk.upper()
  386. log.warn("CIMPortReport.player({0}) : I AM stopping...".format(key))
  387. # Stop the keepalive if we are activating something else
  388. # or leaving...
  389. # self.keepalive.stop()
  390. self.queue_game.put("\b \b\r\n")
  391. if not self.defer is None:
  392. # We have something, so:
  393. self.game.to_player = self.to_player
  394. self.observer.load(self.save)
  395. self.save = None
  396. self.defer.errback(Exception("User Abort"))
  397. self.defer = None
  398. else:
  399. # Still "exit" out.
  400. self.game.to_player = self.to_player
  401. self.observer.load(self.save)
  402. class ScriptPort(object):
  403. """ Performs the Port script.
  404. This is close to the original.
  405. We don't ask for the port to trade with --
  406. because that information is available to us after "D" (display).
  407. We look at the adjacent sectors, and see if we know any ports.
  408. If the ports are burnt (< 20%), we remove them from the list.
  409. If there's just one, we use it. Otherwise we ask them to choose.
  410. """
  411. def __init__(self, game):
  412. self.game = game
  413. self.queue_game = game.queue_game
  414. self.queue_player = game.queue_player
  415. self.observer = game.observer
  416. self.r = Style.RESET_ALL
  417. self.nl = "\n\r"
  418. self.this_sector = None # Starting sector
  419. self.sector1 = None # Current Sector
  420. self.sector2 = None # Next Sector Stop
  421. self.percent = 5 # Stick with the good default.
  422. self.credits = 0
  423. self.last_credits = None
  424. self.times_left = 0
  425. # Activate
  426. self.prompt = game.buffer
  427. self.save = self.observer.save()
  428. self.observer.connect('player', self.player)
  429. self.observer.connect("prompt", self.game_prompt)
  430. self.observer.connect("game-line", self.game_line)
  431. self.defer = None
  432. self.queue_game.put(
  433. self.nl + "Script based on: Port Pair Trading v2.00" + self.r + self.nl
  434. )
  435. self.possible_sectors = None
  436. self.state = 1
  437. self.queue_player.put("D")
  438. # Original, send 'D' to display current sector.
  439. # We could get the sector number from the self.prompt string -- HOWEVER:
  440. # IF! We send 'D', we can also get the sectors around -- we might not even need to
  441. # prompt for sector to trade with (we could possibly figure it out ourselves).
  442. # [Command [TL=00:00:00]:[967] (?=Help)? : D]
  443. # [<Re-Display>]
  444. # []
  445. # [Sector : 967 in uncharted space.]
  446. # [Planets : (M) Into the Darkness]
  447. # [Warps to Sector(s) : 397 - (562) - (639)]
  448. # []
  449. def whenDone(self):
  450. self.defer = defer.Deferred()
  451. # Call this to chain something after we exit.
  452. return self.defer
  453. def deactivate(self):
  454. self.state = 0
  455. log.debug("ScriptPort.deactivate ({0})".format(self.times_left))
  456. assert(not self.save is None)
  457. self.observer.load(self.save)
  458. self.save = None
  459. if self.defer:
  460. self.defer.callback('done')
  461. self.defer = None
  462. def player(self, chunk: bytes):
  463. # If we receive anything -- ABORT!
  464. self.deactivate()
  465. def game_prompt(self, prompt: str):
  466. log.debug("{0} : {1}".format(self.state, prompt))
  467. if self.state == 3:
  468. # log.("game_prompt: ", prompt)
  469. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  470. self.state = 4
  471. log.debug("Ok, state 4")
  472. if self.sector2 is None:
  473. # Ok, we need to prompt for this.
  474. self.queue_game.put(self.r + self.nl +
  475. "Which sector to trade with? {0}".format(GameData.port_show_part(self.this_sector, self.game.gamedata.ports[self.this_sector])) +
  476. self.nl)
  477. for i, p in enumerate(self.possible):
  478. self.queue_game.put(" " + Fore.CYAN + str(i + 1) + " : " + GameData.port_show_part(p, self.game.gamedata.ports[p]) + self.nl)
  479. pi = PlayerInput(self.game)
  480. def got_need1(*_):
  481. log.debug("Ok, I have:", pi.keep)
  482. if pi.keep['count'].strip() == '':
  483. self.deactivate()
  484. return
  485. self.times_left = int(pi.keep['count'])
  486. if pi.keep['choice'].strip() == '':
  487. self.deactivate()
  488. return
  489. c = int(pi.keep['choice']) -1
  490. if c < 0 or c >= len(self.possible):
  491. self.deactivate()
  492. return
  493. self.sector2 = self.possible[int(pi.keep['choice']) -1]
  494. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  495. self.state = 5
  496. self.trade()
  497. d = pi.prompt("Choose -=>", 5, name='choice', digits=True)
  498. d.addCallback(lambda ignore: pi.prompt("Times to execute script:", 5, name='count', digits=True))
  499. d.addCallback(got_need1)
  500. else:
  501. # We already have our target port, so...
  502. self.queue_game.put(self.r + self.nl + "Trading from {0} ({1}) to default {2} ({3}).".format(
  503. self.this_sector,
  504. self.game.gamedata.ports[self.this_sector]['port'],
  505. self.sector2, self.game.gamedata.ports[self.sector2]['port']) + self.nl
  506. )
  507. self.queue_game.put(self.r + self.nl + "Trading {0}".format(
  508. self.game.gamedata.port_trade_show(self.this_sector,
  509. self.sector2)
  510. ))
  511. # The code is smart enough now, that this can't happen. :( Drat!
  512. if self.game.gamedata.ports[self.this_sector]['port'] == self.game.gamedata.ports[self.sector2]['port']:
  513. self.queue_game.put("Hey dummy! Look out the window! These ports are the same class!" + nl)
  514. self.deactivate()
  515. return
  516. pi = PlayerInput(self.game)
  517. def got_need2(*_):
  518. if pi.keep['count'].strip() == '':
  519. self.deactivate()
  520. return
  521. self.times_left = int(pi.keep['count'])
  522. log.debug("Ok, I have:", pi.keep)
  523. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  524. self.state = 5
  525. self.trade()
  526. self.queue_game.put(self.r + self.nl)
  527. d = pi.prompt("Times to execute script", 5, name='count')
  528. d.addCallback(got_need2)
  529. elif self.state == 6:
  530. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  531. if self.fixable:
  532. self.queue_game.put("Ok! Let's fix this by going to the other sector..." + self.nl)
  533. log.debug("Fixing...")
  534. if self.this_sector == self.sector1:
  535. self.this_sector = self.sector2
  536. self.queue_player.put("{0}\r".format(self.sector2))
  537. self.state = 5
  538. self.trade()
  539. else:
  540. self.this_sector = self.sector1
  541. self.queue_player.put("{0}\r".format(self.sector1))
  542. self.state = 5
  543. self.trade()
  544. elif self.state == 7:
  545. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  546. # Done
  547. if self.this_sector == self.sector1:
  548. self.this_sector = self.sector2
  549. self.queue_player.put("{0}\r".format(self.sector2))
  550. self.state = 10
  551. else:
  552. self.times_left -= 1
  553. if self.times_left <= 0:
  554. # Ok, exit out
  555. self.deactivate()
  556. return
  557. if self.last_credits is None:
  558. self.last_credits = self.credits
  559. else:
  560. if self.credits <= self.last_credits:
  561. log.warn("We don't seem to be making any money here...")
  562. self.queue_game.put(self.r + self.nl + "We don't seem to be making any money here. I'm stopping!" + self.nl)
  563. self.deactivate()
  564. return
  565. self.this_sector = self.sector1
  566. self.queue_player.put("{0}\r".format(self.sector1))
  567. self.state = 10
  568. elif re.match(r'Your offer \[\d+\] \?', prompt):
  569. if self.fix_offer:
  570. # Make real offer / WHAT?@?!
  571. work = prompt.replace(',', '')
  572. parts = re.split(r"\s+", work)
  573. amount = parts[2]
  574. # Ok, we have the amount, now to figure pct...
  575. if self.sell_pct > 100:
  576. self.sell_pct -= 1
  577. else:
  578. self.sell_pct += 1
  579. price = amount * self.sell_pct // 100
  580. log.debug("start: {0} % {1} price {2}".format(amount, self.sell_perc, price))
  581. if self.sell_pct > 100:
  582. self.sell_pct -= 1
  583. else:
  584. self.sell_pct += 1
  585. self.queue_player.put("{0}\r".format(price))
  586. elif self.state == 8:
  587. # What are we trading
  588. # How many holds of Equipment do you want to buy [75]?
  589. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\?", prompt):
  590. parts = prompt.split()
  591. trade_type = parts[4]
  592. if trade_type == 'Fuel':
  593. if (self.tpc in (5,7)) and (self.opc in (2,3,4,8)):
  594. # Can buy equipment - fuel ore is worthless.
  595. self.queue_player.put("0\r")
  596. return
  597. if (self.tpc in(4,7)) and (self.opc in (1,3,5,8)):
  598. # Can buy organics - fuel ore is worthless.
  599. self.queue_player.put("0\r")
  600. return
  601. if (self.tpc in (4,7,3,5)) and (self.opc in (3,4,5,7)):
  602. # No point in buying fuel ore if it can't be sold.
  603. self.queue_player.put("0\r")
  604. return
  605. elif trade_type == 'Organics':
  606. if (self.tpc in (6,7)) and (self.opc in (2,3,4,8)):
  607. # Can buy equipment - organics is worthless.
  608. self.queue_player.put("0\r")
  609. return
  610. if (self.tpc in (2,4,6,7)) and (self.opc in (2,4,6,7)):
  611. # No point in buying organics if it can't be sold.
  612. self.queue_player.put("0\r")
  613. return
  614. elif trade_type == 'Equipment':
  615. if (self.opc in (1,5,6,7)):
  616. # No point in buying equipment if it can't be sold.
  617. self.queue_player.put("0\r")
  618. return
  619. self.queue_player.put("\r")
  620. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  621. # Done
  622. if self.this_sector == self.sector1:
  623. self.this_sector = self.sector2
  624. self.queue_player.put("{0}\r".format(self.sector2))
  625. self.state = 10
  626. else:
  627. self.times_left -= 1
  628. if self.times_left <= 0:
  629. # Ok, exit out
  630. self.deactivate()
  631. return
  632. if self.last_credits is None:
  633. self.last_credits = self.credits
  634. else:
  635. if self.credits <= self.last_credits:
  636. log.warn("We don't seem to be making any money here...")
  637. self.deactivate()
  638. return
  639. self.this_sector = self.sector1
  640. self.queue_player.put("{0}\r".format(self.sector1))
  641. self.state = 10
  642. def trade(self, *_):
  643. # state 5
  644. log.debug("trade!")
  645. self.queue_player.put("pt") # Port Trade
  646. self.this_port = self.game.gamedata.ports[self.this_sector]
  647. if self.this_sector == self.sector1:
  648. self.other_port = self.game.gamedata.ports[self.sector2]
  649. else:
  650. self.other_port = self.game.gamedata.ports[self.sector1]
  651. # Ok, perform some calculations
  652. self.tpc = self.this_port['class']
  653. self.opc = self.other_port['class']
  654. self.fixable = 0
  655. self.fix_offer = 0
  656. # [ Items Status Trading % of max OnBoard]
  657. # [ ----- ------ ------- -------- -------]
  658. # [Fuel Ore Selling 2573 93% 0]
  659. # [Organics Buying 2960 100% 0]
  660. # [Equipment Buying 1958 86% 0]
  661. # []
  662. # []
  663. # [You have 1,000 credits and 20 empty cargo holds.]
  664. # []
  665. # [We are selling up to 2573. You have 0 in your holds.]
  666. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  667. def game_line(self, line: str):
  668. if line.startswith("You have ") and 'credits and' in line:
  669. parts = line.replace(',', '').split()
  670. credits = int(parts[2])
  671. log.debug("Credits: {0}".format(credits))
  672. self.credits = credits
  673. if self.state == 1:
  674. # First exploration
  675. if line.startswith("Sector :"):
  676. # We have starting sector information
  677. parts = re.split("\s+", line)
  678. self.this_sector = int(parts[2])
  679. # These will be the ones swapped around as we trade back and forth.
  680. self.sector1 = self.this_sector
  681. elif line.startswith("Warps to Sector(s) : "):
  682. # Warps to Sector(s) : 397 - (562) - (639)
  683. _, _, warps = line.partition(':')
  684. warps = warps.replace('-', '').replace('(', '').replace(')', '').strip()
  685. log.debug("Warps: [{0}]".format(warps))
  686. self.warps = [ int(x) for x in re.split("\s+", warps)]
  687. log.debug("Warps: [{0}]".format(self.warps))
  688. self.state = 2
  689. elif self.state == 2:
  690. if line == "":
  691. # Ok, we're done
  692. self.state = 3
  693. # Check to see if we have information on any possible ports
  694. # if hasattr(self.game, 'portdata'):
  695. if True:
  696. if not self.this_sector in self.game.gamedata.ports:
  697. self.state = 0
  698. log.debug("Current sector {0} not in portdata.".format(self.this_sector))
  699. self.queue_game.put(self.r + self.nl + "I can't find the current sector in the portdata." + self.nl)
  700. self.deactivate()
  701. return
  702. else:
  703. # Ok, we are in the portdata
  704. pd = self.game.gamedata.ports[self.this_sector]
  705. if GameData.port_burnt(pd):
  706. log.debug("Current sector {0} port is burnt (<= 20%).".format(self.this_sector))
  707. self.queue_game.put(self.r + self.nl + "Current sector port is burnt out. <= 20%." + self.nl)
  708. self.deactivate()
  709. return
  710. possible = [ x for x in self.warps if x in self.game.gamedata.ports ]
  711. log.debug("Possible:", possible)
  712. # BUG: Sometimes links to another sector, don't link back!
  713. # This causes the game to plot a course / autopilot.
  714. # if hasattr(self.game, 'warpdata'):
  715. if True:
  716. # Great! verify that those warps link back to us!
  717. possible = [ x for x in possible if x in self.game.gamedata.warps and self.this_sector in self.game.gamedata.warps[x]]
  718. if len(possible) == 0:
  719. self.state = 0
  720. self.queue_game.put(self.r + self.nl + "I don't see any ports in [{0}].".format(self.warps) + self.nl)
  721. self.deactivate()
  722. return
  723. possible = [ x for x in possible if not GameData.port_burnt(self.game.gamedata.ports[x]) ]
  724. log.debug("Possible:", possible)
  725. if len(possible) == 0:
  726. self.state = 0
  727. self.queue_game.put(self.r + self.nl + "I don't see any unburnt ports in [{0}].".format(self.warps) + self.nl)
  728. self.deactivate()
  729. return
  730. possible = [ x for x in possible if GameData.port_trading(self.game.gamedata.ports[self.this_sector]['port'], self.game.gamedata.ports[x]['port'])]
  731. self.possible = possible
  732. if len(possible) == 0:
  733. self.state = 0
  734. self.queue_game.put(self.r + self.nl + "I don't see any possible port trades in [{0}].".format(self.warps) + self.nl)
  735. self.deactivate()
  736. return
  737. elif len(possible) == 1:
  738. # Ok! there's only one!
  739. self.sector2 = possible[0]
  740. # Display possible ports:
  741. # spos = [ str(x) for x in possible]
  742. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  743. # At state 3, we only get a prompt.
  744. return
  745. else:
  746. self.state = 0
  747. log.warn("We don't have any portdata!")
  748. self.queue_game.put(self.r + self.nl + "I have no portdata. Please run CIM Port Report." + self.nl)
  749. self.deactivate()
  750. return
  751. elif self.state == 5:
  752. if "-----" in line:
  753. self.state = 6
  754. elif self.state == 6:
  755. if "We are buying up to" in line:
  756. # Sell
  757. self.state = 7
  758. self.queue_player.put("\r")
  759. self.sell_perc = 100 + self.percent
  760. if "We are selling up to" in line:
  761. # Buy
  762. self.state = 8
  763. self.sell_perc = 100 - self.percent
  764. if line.startswith('Fuel Ore') or line.startswith('Organics') or line.startswith('Equipment'):
  765. work = line.replace('Fuel Ore', 'Fuel')
  766. parts = re.split(r"\s+", work)
  767. # log.debug(parts)
  768. # Equipment, Selling xxx x% xxx
  769. if parts[-1] != '0' and parts[2] != '0' and parts[1] != 'Buying':
  770. log.warn("We have a problem -- they aren't buying what we have in stock!")
  771. stuff = line[0] # F O or E.
  772. if stuff == 'F':
  773. spos = 0
  774. elif stuff == 'O':
  775. spos = 1
  776. else:
  777. spos = 2
  778. other = self.other_port['port']
  779. if other[spos] == 'B':
  780. self.fixable = 1
  781. if "You don't have anything they want" in line:
  782. # Neither! DRAT!
  783. if not self.fixable:
  784. self.deactivate()
  785. return
  786. if "We're not interested." in line:
  787. log.warn("Try, try again. :(")
  788. self.state = 5
  789. self.trade()
  790. elif self.state == 7:
  791. # Haggle Sell
  792. if "We'll buy them for" in line or "Our final offer" in line:
  793. if "Our final offer" in line:
  794. self.sell_perc -= 1
  795. parts = line.replace(',', '').split()
  796. start_price = int(parts[4])
  797. price = start_price * self.sell_perc // 100
  798. log.debug("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  799. self.sell_perc -= 1
  800. self.queue_player.put("{0}\r".format(price))
  801. if "We are selling up to" in line:
  802. # Buy
  803. self.state = 8
  804. self.sell_perc = 100 - self.percent
  805. if "We're not interested." in line:
  806. log.info("Try, try again. :(")
  807. self.state = 5
  808. self.trade()
  809. if "WHAT?!@!? you must be crazy!" in line:
  810. log.warn("fix offer")
  811. self.fix_offer = 1
  812. if "So, you think I'm as stupid as you look?" in line:
  813. log.warn("fix offer")
  814. self.fix_offer = 1
  815. if "Quit playing around, you're wasting my time!" in line:
  816. log.warn("fix offer")
  817. self.fix_offer = 1
  818. elif self.state == 8:
  819. # Haggle Buy
  820. if "We'll sell them for" in line or "Our final offer" in line:
  821. if "Our final offer" in line:
  822. self.sell_perc += 1
  823. parts = line.replace(',', '').split()
  824. start_price = int(parts[4])
  825. price = start_price * self.sell_perc // 100
  826. log.debug("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  827. self.sell_perc += 1
  828. self.queue_player.put("{0}\r".format(price))
  829. if "We're not interested." in line:
  830. log.info("Try, try again. :(")
  831. self.state = 5
  832. self.trade()
  833. elif self.state == 10:
  834. if "Sector : " in line:
  835. # Trade
  836. self.state = 5
  837. reactor.callLater(0, self.trade, 0)
  838. # self.trade()
  839. # elif self.state == 3:
  840. # log.debug("At state 3 [{0}]".format(line))
  841. # self.queue_game.put("At state 3.")
  842. # self.deactivate()
  843. # return
  844. class ScriptExplore(object):
  845. """ Script Explore v1.00
  846. By: David Thielemann
  847. WARNINGS:
  848. We assume the player has a Holo-Scanner!
  849. We assume the player has lots o turns, or unlimited turns!
  850. We assume the player is aware we run infinitely until we can't find new sectors to move to!
  851. """
  852. def __init__(self, game):
  853. self.game = game
  854. self.queue_game = game.queue_game
  855. self.queue_player = game.queue_player
  856. self.observer = game.observer
  857. self.r = Style.RESET_ALL
  858. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  859. self.nl = "\n\r"
  860. # Our Stuff, Not our pants!
  861. self.dense = [] # We did a density, store that info.
  862. self.clear = [] # Warps that we know are clear.
  863. self.didDense = False
  864. self.didHolo = False
  865. self.highsector = 0 # Selected Sector to move to next!
  866. self.highwarp = 0 # Selected Sector's Warp Count!
  867. self.stacksector = set() # Set of sectors that we have not picked but are unexplored... even though we did a holo!
  868. self.oneMoveSector = False
  869. self.times = 0
  870. self.maxtimes = 0
  871. # Activate
  872. self.prompt = game.buffer
  873. self.save = self.observer.save()
  874. self.observer.connect('player', self.player)
  875. self.observer.connect("prompt", self.game_prompt)
  876. self.observer.connect("game-line", self.game_line)
  877. self.defer = None
  878. self.send2player(Boxes.alert("Explorer v1.01", base="green"))
  879. # How many times we going to go today?
  880. ask = PlayerInput(self.game)
  881. def settimes(*_):
  882. times = ask.keep['times'].strip()
  883. log.debug("settimes got '{0}'".format(times))
  884. if times == '':
  885. self.deactivate()
  886. else:
  887. times = int(times)
  888. self.times = times
  889. self.maxtimes = times
  890. self.send2game("D")
  891. self.state = 1
  892. d = ask.prompt("How many sectors would you like to explorer?", 5, name="times", digits=True)
  893. #d.addCallback(ask.output)
  894. #d.addCallback(lambda ignore: self.settimes(ask.keep))
  895. d.addCallback(settimes)
  896. def whenDone(self):
  897. self.defer = defer.Deferred()
  898. # Call this to chain something after we exit.
  899. return self.defer
  900. def deactivate(self):
  901. self.state = 0
  902. log.debug("ScriptExplore.deactivate()")
  903. assert(not self.save is None)
  904. self.observer.load(self.save)
  905. self.save = None
  906. if self.defer:
  907. self.defer.callback('done')
  908. self.defer = None
  909. def player(self, chunk: bytes):
  910. # If we receive anything -- ABORT!
  911. self.deactivate()
  912. def send2game(self, txt):
  913. self.queue_player.put(txt)
  914. def send2player(self, txt):
  915. self.queue_game.put(
  916. self.nl + txt + self.r + self.nl
  917. )
  918. def resetStuff(self):
  919. self.didDense = False
  920. self.didHolo = False
  921. self.dense = []
  922. self.clear = []
  923. self.highwarp = 0
  924. self.highsector = 0
  925. log.debug("ScriptExplore.resetStuff()")
  926. def dead_end(self):
  927. """ We've reached a dead end.
  928. Either pop a new location to travel to, or give it up.
  929. """
  930. self.send2player(Boxes.alert("** DEAD END **", base="blue"))
  931. if self.stacksector:
  932. # Ok, there's somewhere to go ...
  933. self.highsector = self.stacksector.pop()
  934. # travel state
  935. self.state = 10
  936. self.send2game("{0}\r".format(self.highsector))
  937. else:
  938. self.send2player(Boxes.alert("I've run out of places to look ({0}/{1}).".format(self.maxtimes - self.times, self.maxtimes)))
  939. self.deactivate()
  940. def game_over(self, msg):
  941. self.send2player(Boxes.alert("STOP: {0} ({1}/{2}).".format(msg, self.maxtimes - self.times, self.maxtimes)))
  942. self.deactivate()
  943. def game_prompt(self, prompt: str):
  944. log.debug("{0} : {1}".format(self.state, prompt))
  945. if self.state == 2:
  946. if "Select (H)olo Scan or (D)ensity Scan or (Q)uit" in prompt:
  947. self.send2game("D")
  948. # self.state += 1
  949. elif self.state == 5:
  950. log.debug("dense is {0} sectors big".format(len(self.dense)))
  951. self.state += 1
  952. self.send2game("SH")
  953. elif self.state == 12:
  954. # Looking for "Engage the Autopilot?"
  955. if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
  956. self.send2game("S")
  957. self.travel_path.pop(0)
  958. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
  959. self.send2game("SD")
  960. self.state += 1
  961. # Arriving sector :1691 Autopilot disengaging.
  962. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  963. log.info("We made it to where we wanted to go!")
  964. # can't init state 1, because we're at a prompt, so...
  965. self.send2game("S")
  966. self.state = 2
  967. return
  968. elif self.state == 15:
  969. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
  970. self.send2game("N")
  971. self.travel_path.pop(0)
  972. self.state = 12
  973. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  974. log.info("We made it to where we wanted to go!")
  975. # can't init state 1, because we're at a prompt, so...
  976. self.send2game("S")
  977. self.state = 2
  978. return
  979. elif self.state == 20:
  980. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]'):
  981. # Stop in this sector / Yes!
  982. self.send2game("Y")
  983. self.state = 1
  984. # this should re-trigger a scan
  985. def game_line(self, line: str):
  986. log.debug("{0} | {1}".format(self.state, line))
  987. #if "Mine Control" in line: # If we don't have a Holo-Scanner and we attempted to do a Holo-scan, abort
  988. # self.deactivate()
  989. if self.state == 1:
  990. self.send2game("S")
  991. self.state += 1
  992. elif self.state == 2:
  993. if "Relative Density Scan" in line:
  994. self.state = 3
  995. elif "You don't have a long range scanner." in line:
  996. log.warn("FATAL: No Long Range Scanner Installed!")
  997. self.send2player(Boxes.alert("You need a Long Range Scanner!"))
  998. self.deactivate()
  999. return
  1000. # elif "Long Range Scan" in line:
  1001. # self.state += 1
  1002. elif self.state == 3:
  1003. # Get the Density Data!
  1004. if line.startswith("Sector"):
  1005. new_sector = '(' in line
  1006. work = line.replace(':', '').replace(')', '').replace('(', '').replace('%', '').replace('==>', '')
  1007. work = re.split(r"\s+", work)
  1008. log.debug(work)
  1009. # 'Sector', '8192', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  1010. # 'Sector', '(', '8192)', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  1011. # New Sector?
  1012. if new_sector:
  1013. # Switch Anom into bool state
  1014. # if(work[8] == 'No'):
  1015. # temp = False
  1016. # else:
  1017. # temp = True
  1018. #self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': temp} )
  1019. self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': work[8] == 'Yes'} )
  1020. log.debug(self.dense)
  1021. # {'sector': 8192, 'density': 0, 'warps': 4, 'navhaz': 0, 'anom': False}
  1022. elif line == "":
  1023. self.state += 1
  1024. # yeah, this would be better in the above line...
  1025. # leaving it for now.
  1026. # Which is why I broke the elif chain. ...
  1027. if self.state == 4:
  1028. # Begin Processing our data we got from density scan and find highest warp count in what sectors
  1029. # Remove sectors with one warp
  1030. log.debug("state 4: {0}".format(self.dense))
  1031. # Do we have a new place to go? (That is also worth going to)
  1032. if not self.dense: # Dense contains no new sectors, abort
  1033. log.info("No New Sectors Found!")
  1034. self.dead_end()
  1035. return
  1036. # self.send2player(Boxes.alert("Find a new area for me to search in!"))
  1037. # Attempt to resolve no new sectors!
  1038. # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
  1039. # self.highsector = self.stacksector.pop()
  1040. # self.deactivate()
  1041. # elif self.dense: # Dense does contain at least 1 new sector, continue on
  1042. # ugh, actually, we don't care about making a list
  1043. # we only want to know if there's any that have warps > 1. :(
  1044. # see any:
  1045. # list comprehension
  1046. # t = [d for d in self.dense if d['warps'] > 1]
  1047. # t = [] # Pre-Test to check if there are just a bunch of 1 warp sectors
  1048. # for d in self.dense:
  1049. # if d['warps'] > 1:
  1050. # t.append(d['sector'])
  1051. # I don't care if there's only one warp. if it's un-explorered then
  1052. # explore it!
  1053. # if not any( w['warps'] > 1 for w in self.dense):
  1054. # # If there are no sectors with more that 1 warp, abort
  1055. # log.debug("No Sectors Found except one move sector!")
  1056. # self.dead_end()
  1057. # return
  1058. # self.send2player(Boxes.alert("Find a new area for me to look at!"))
  1059. # Attempt to resolve no new sectors with more than 1 warp!
  1060. # if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
  1061. # self.highsector = self.stacksector.pop()
  1062. # self.deactivate()
  1063. # Is the sector safe to go into?
  1064. # 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 ]
  1065. self.clear = [ x for x in self.dense if not x['anom'] and not x['navhaz'] and x['density'] in (0,1,100,101) ]
  1066. # for d in self.dense:
  1067. # if not d['anom']:
  1068. # # Sector does not contain a Anomoly
  1069. # if not d['navhaz']:
  1070. # # Sector does not contain Hazards
  1071. # if d['density'] in (0, 1, 100, 101):
  1072. # # Sector does contain empty space / a beacon / a port / or a beacon and port
  1073. # if d['warps'] > 1:
  1074. # # If Sector is worth checking out?
  1075. # self.clear.append(d['sector'])
  1076. if self.clear: # We have sector(s) we can move to!
  1077. log.debug("Clear Sectors: {0}".format(len(self.clear)))
  1078. # 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 )
  1079. # Sort to find greatest warp count
  1080. self.highwarp, self.highsector = max( (x['warps'], x['sector']) for x in self.clear)
  1081. # for c in self.clear:
  1082. # for d in self.dense:
  1083. # if d['sector'] == c:
  1084. # if d['warps'] > self.highwarp:
  1085. # self.highwarp = d['warps']
  1086. # self.highsector = d['sector']
  1087. # elif d['warps'] == self.highwarp:
  1088. # if d['sector'] > self.highsector:
  1089. # self.highsector = d['sector']
  1090. # if self.highwarp and self.highsector:
  1091. log.info("Sector: {0:5d} Warps: {1}".format(self.highsector, self.highwarp))
  1092. self.state += 1
  1093. else:
  1094. log.warn("No (safe) sectors to move to!")
  1095. # Let's try this?!
  1096. # self.dead_end() # NO!
  1097. self.game_over("No SAFE moves.")
  1098. # Another NOP state. This also could be merged into above.
  1099. # break the elif chain.
  1100. if self.state == 5:
  1101. # Add the dense scan of unknown sectors onto the stack of sectors, only save the ones we think are clear... for now.
  1102. for c in self.clear:
  1103. sector = c['sector']
  1104. if sector != self.highsector:
  1105. self.stacksector.add(sector)
  1106. # Or simply not add it in the first place ...
  1107. # 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!
  1108. # self.stacksector.discard(self.highsector)
  1109. # Ok, we need to decide to stop exploring -- before we
  1110. # issue the sector move! :P
  1111. #
  1112. # Warning! Yes we can and will eat all the turns! :P
  1113. if self.times == 0:
  1114. self.send2player(Boxes.alert("Completed {0}".format(self.maxtimes), base="green"))
  1115. log.info("Completed {0}".format(self.maxtimes))
  1116. self.deactivate()
  1117. return
  1118. self.times -= 1
  1119. # Ok we know the sector we want to go to now let's move it!
  1120. self.send2game("m{0}\r".format(self.highsector))
  1121. # Reset Variables for fresh data
  1122. self.resetStuff()
  1123. self.state = 1
  1124. elif self.state == 10:
  1125. if line.startswith("You are already in that sector!"):
  1126. log.info("Already here. (Whoops!)")
  1127. self.state = 1
  1128. return
  1129. if line.startswith("Sector : {0}".format(self.highsector)):
  1130. log.info("We're here!")
  1131. # Ok, we're already there! no autopilot needed!
  1132. self.state = 1
  1133. return
  1134. # Warping
  1135. self.go_on = True
  1136. if line.startswith('The shortest path ('):
  1137. # Ok, we've got a path.
  1138. self.state += 1
  1139. elif self.state == 11:
  1140. # TOFIX: This can be multiple lines
  1141. self.travel_path = line.replace('(', '').replace(')', '').split(' > ')
  1142. log.debug("Travel path: {0}".format(self.travel_path))
  1143. self.state += 1
  1144. self.travel_path.pop(0) # First sector is one we're in.
  1145. self.stophere = False
  1146. self.go_on = True
  1147. elif self.state == 12:
  1148. # Arriving sector :1691 Autopilot disengaging.
  1149. if 'Autopilot disengaging.' in line:
  1150. log.info("We made it to where we wanted to go!")
  1151. self.state = 1
  1152. return
  1153. elif self.state == 13:
  1154. if 'Relative Density Scan' in line:
  1155. self.state += 1
  1156. elif self.state == 14:
  1157. if line == "":
  1158. log.debug("PATH: {0}".format(self.travel_path))
  1159. # end of the scan, decision time
  1160. if self.stophere:
  1161. log.info("STOPHERE")
  1162. # Ok, let's stop here!
  1163. # Re-save the sector we were trying to get to. (we didn't make it there)
  1164. self.stacksector.add(self.highsector)
  1165. self.state = 20
  1166. else:
  1167. if self.go_on:
  1168. log.info("GO ON")
  1169. # Ok, carry on!
  1170. self.state = 15
  1171. else:
  1172. log.warn("Our way is blocked...")
  1173. self.stacksector.add(self.highsector)
  1174. self.state = 20
  1175. else:
  1176. if line.strip('-') != '':
  1177. work = line.replace(' :', '').replace('%', '').replace(')', '').replace('==>', '')
  1178. # Does this contain something new? unseen?
  1179. stophere = '(' in work
  1180. work = work.replace('(','')
  1181. #Sector XXXX DENS Warps N NavHaz P Anom YN
  1182. parts = re.split(r'\s+', work)
  1183. # Don't bother stopping if there's only one warp
  1184. # YES! Stop, even if there is just one warp!
  1185. # if stophere and parts[4] == '1':
  1186. # stophere = False
  1187. if stophere:
  1188. self.stophere = True
  1189. next_stop = self.travel_path[0]
  1190. log.debug("next_stop {0} from {1}".format(next_stop, self.travel_path))
  1191. log.debug("parts: {0}".format(parts))
  1192. if parts[1] == next_stop:
  1193. log.info("next_stop {0} found...".format(next_stop))
  1194. # Ok, this is our next stop. Is it safe to travel to?
  1195. if parts[2] not in ('100', '0', '1', '101'):
  1196. # Ok, it's not safe to go on.
  1197. self.go_on = False
  1198. # Check the rest navhav and anom ...
  1199. class ScriptSpace(object):
  1200. """ Space Exploration script.
  1201. Send "SD", verify paths are clear.
  1202. Find nearest unknown. Sector + CR.
  1203. Save "shortest path from to" information.
  1204. At 'Engage the Autopilot', Send "S" (Single Step)
  1205. At '[Stop in this sector', Send "SD", verify path is clear.
  1206. Send "SH" (glean sector/port information along the way.)
  1207. Send "N" (Next)!
  1208. Send "SD" / Verify clear.
  1209. Send "SH"
  1210. Repeat for Next closest.
  1211. """
  1212. def __init__(self, game):
  1213. self.game = game
  1214. self.queue_game = game.queue_game
  1215. self.queue_player = game.queue_player
  1216. self.observer = game.observer
  1217. self.r = Style.RESET_ALL
  1218. self.nl = "\n\r"
  1219. self.this_sector = None # Starting sector
  1220. self.target_sector = None # Sector going to
  1221. self.path = []
  1222. self.times_left = 0 # How many times to look for target
  1223. self.density = dict() # Results of density scan. (Just the numbers)
  1224. # Activate
  1225. self.prompt = game.buffer
  1226. self.save = self.observer.save()
  1227. self.observer.connect('player', self.player)
  1228. self.observer.connect("prompt", self.game_prompt)
  1229. self.observer.connect("game-line", self.game_line)
  1230. self.defer = None
  1231. self.queue_game.put(
  1232. self.nl + "Bugz (like space), is big." + self.r + self.nl
  1233. )
  1234. self.state = 1
  1235. self.queue_player.put("SD")
  1236. # Get current density scan + also get the current sector.
  1237. # [Command [TL=00:00:00]:[XXXX] (?=Help)? : D]
  1238. def whenDone(self):
  1239. self.defer = defer.Deferred()
  1240. # Call this to chain something after we exit.
  1241. return self.defer
  1242. def deactivate(self):
  1243. self.state = 0
  1244. log.debug("ScriptPort.deactivate ({0})".format(self.times_left))
  1245. assert(not self.save is None)
  1246. self.observer.load(self.save)
  1247. self.save = None
  1248. if self.defer:
  1249. self.defer.callback('done')
  1250. self.defer = None
  1251. def player(self, chunk: bytes):
  1252. # If we receive anything -- ABORT!
  1253. self.deactivate()
  1254. def unknown_search(self, starting_sector):
  1255. seen = set()
  1256. possible = set()
  1257. possible.add(int(starting_sector))
  1258. done = False
  1259. while not done:
  1260. next_possible = set()
  1261. for s in possible:
  1262. p = self.game.gamedata.get_warps(s)
  1263. if p is not None:
  1264. for pos in p:
  1265. if pos not in seen:
  1266. next_possible.add(pos)
  1267. else:
  1268. log.debug("unknown found:", s)
  1269. self.unknown = s
  1270. done = True
  1271. break
  1272. seen.add(s)
  1273. if self.unknown is None:
  1274. log.debug("possible:", next_possible)
  1275. possible = next_possible
  1276. yield
  1277. def find_unknown(self, starting_sector):
  1278. log.debug("find_unknown( {0})".format(starting_sector))
  1279. d = defer.Deferred()
  1280. # Process things
  1281. self.unknown = None
  1282. c = coiterate(self.unknown_search(starting_sector))
  1283. c.addCallback(lambda unknown: d.callback(self.unknown))
  1284. return d
  1285. def show_unknown(self, sector):
  1286. if sector is None:
  1287. self.deactivate()
  1288. return
  1289. log.debug("Travel to {0}...".format(sector))
  1290. self.queue_player.put("{0}\r".format(sector))
  1291. def game_prompt(self, prompt: str):
  1292. log.debug("{0} : {1}".format(self.state, prompt))
  1293. if self.state == 3:
  1294. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1295. # this_sector code isn't working -- so! Get sector from prompt
  1296. self.state = 4
  1297. _, _, sector = prompt.partition(']:[')
  1298. sector, _, _ = sector.partition(']')
  1299. self.this_sector = int(sector)
  1300. # Ok, we're done with Density Scan, and we're back at the command prompt
  1301. log.debug("Go find the nearest unknown...")
  1302. d = self.find_unknown(sector)
  1303. d.addCallback(self.show_unknown)
  1304. elif self.state == 6:
  1305. # Engage the autopilot?
  1306. if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
  1307. self.state = 7
  1308. sector = self.path.pop(0)
  1309. if sector in self.density:
  1310. if self.density[sector] in (0, 100):
  1311. # Ok, looks safe!
  1312. self.queue_player.put("S")
  1313. self.this_sector = sector
  1314. else:
  1315. log.warn("FATAL: Density for {0} is {1}".format(sector, self.density[sector]))
  1316. self.deactivate()
  1317. return
  1318. else:
  1319. log.error("{0} not in density scan? (how's that possible?)".format(sector))
  1320. self.deactivate()
  1321. return
  1322. elif self.state == 7:
  1323. # Ok, we're in a new sector (single stepping through space)
  1324. # update density scan
  1325. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1326. self.queue_player.put("SD")
  1327. self.state = 8
  1328. elif self.state == 10:
  1329. # Because we're here
  1330. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1331. self.queue_player.put("SH")
  1332. self.state = 11
  1333. elif self.state == 11:
  1334. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1335. # Ok, is the density scan clear?
  1336. sector = self.path.pop(0)
  1337. if sector in self.density:
  1338. if self.density[sector] in (0, 100):
  1339. # Ok, looks safe
  1340. self.queue_player.put("N")
  1341. self.state = 7
  1342. self.this_sector = sector
  1343. else:
  1344. log.warn("FATAL: Density for {0} is {1}".format(sector, self.density[sector]))
  1345. self.deactivate()
  1346. return
  1347. else:
  1348. log.error("{0} not in density scane? (how's that possible...)".format(sector))
  1349. self.deactivate()
  1350. return
  1351. def next_unknown(self, sector):
  1352. log.info("Unknown is :", sector)
  1353. self.deactivate()
  1354. def game_line(self, line: str):
  1355. log.debug("line {0} : {1}".format(self.state, line))
  1356. if line.startswith('Sector : '):
  1357. work = line.strip()
  1358. parts = re.split(r"\s+", work)
  1359. self.this_sector = int(parts[2])
  1360. log.debug("game_line sector", self.this_sector)
  1361. elif line.startswith("Command [TL=]"):
  1362. # Ok, get the current sector from this
  1363. _, _, sector = line.partition("]:[")
  1364. sector, _, _ = sector.partition("]")
  1365. self.this_sector = int(sector)
  1366. log.debug("current sector: {0}".format(self.this_sector))
  1367. elif line.startswith('Warps to Sector(s) :'):
  1368. # Warps to Sector(s) : 5468
  1369. _, _, work = line.partition(':')
  1370. work = work.strip().replace('(', '').replace(')', '').replace(' - ', ' ')
  1371. parts = [ int(x) for x in work.split(' ')]
  1372. self.path = list(parts)
  1373. if self.state in (1, 8):
  1374. if 'Relative Density Scan' in line:
  1375. # Start Density Scan
  1376. self.state += 1
  1377. self.density = {}
  1378. elif self.state in (2, 9):
  1379. if line == '':
  1380. # End of Density Scan
  1381. self.state += 1
  1382. log.debug("Density: {0}".format(self.density))
  1383. # self.deactivate()
  1384. elif line.startswith('Sector'):
  1385. # Parse Density Scan values
  1386. work = line.replace('(', '').replace(')', '').replace(':', '').replace('%', '').replace(',', '')
  1387. parts = re.split(r'\s+', work)
  1388. log.debug("Sector", parts)
  1389. sector = int(parts[1])
  1390. self.density[sector] = int(parts[3])
  1391. if parts[7] != '0':
  1392. log.warn("NavHaz {0} : {1}".format(parts[7], work))
  1393. self.density[sector] += 99
  1394. if parts[9] != 'No':
  1395. log.warn("Anom {0} : {1}".format(parts[9], work))
  1396. self.density[sector] += 990
  1397. elif self.state == 4:
  1398. # Looking for shortest path message / warp info
  1399. # Or possibly, "We're here!"
  1400. if line.startswith('Sector :') and str(self.unknown) in line:
  1401. # Ok, I'd guess that we're already there!
  1402. # Try it again!
  1403. self.queue_player.put("SD")
  1404. self.state = 1
  1405. if line.startswith('The shortest path'):
  1406. self.state = 5
  1407. elif self.state == 5:
  1408. # This is the warps line
  1409. # Can this be multiple lines?
  1410. if line == "":
  1411. self.state = 6
  1412. else:
  1413. work = line.replace("(", "").replace(")", "").replace(">", "").strip()
  1414. self.path = [int(x) for x in work.split()]
  1415. log.debug("Path:", self.path)
  1416. # Verify
  1417. current = self.path.pop(0)
  1418. if current != self.this_sector:
  1419. log.warn("Failed: {0} != {1}".format(current, self.this_sector))
  1420. self.deactivate()
  1421. return
  1422. elif self.state == 7:
  1423. if self.unknown == self.this_sector:
  1424. # We have arrived!
  1425. log.info("We're here!")
  1426. self.deactivate()
  1427. from boxes import Boxes
  1428. class ProxyMenu(object):
  1429. """ Display ProxyMenu
  1430. Example:
  1431. from flexible import ProxyMenu
  1432. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1433. menu = ProxyMenu(self.game)
  1434. """
  1435. def __init__(self, game):
  1436. self.nl = "\n\r"
  1437. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  1438. self.r = Style.RESET_ALL
  1439. self.c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  1440. self.c2 = merge(Style.NORMAL + Fore.CYAN + Back.BLUE)
  1441. # self.portdata = None
  1442. self.game = game
  1443. self.queue_game = game.queue_game
  1444. self.observer = game.observer
  1445. # Am I using self or game? (I think I want game, not self.)
  1446. # if hasattr(self.game, "portdata"):
  1447. # self.portdata = self.game.portdata
  1448. # else:
  1449. # self.portdata = {}
  1450. # if hasattr(self.game, 'warpdata'):
  1451. # self.warpdata = self.game.warpdata
  1452. # else:
  1453. # self.warpdata = {}
  1454. if hasattr(self.game, 'trade_report'):
  1455. self.trade_report = self.game.trade_report
  1456. else:
  1457. self.trade_report = []
  1458. # Yes, at this point we would activate
  1459. self.prompt = game.buffer
  1460. self.save = self.observer.save()
  1461. self.observer.connect("player", self.player)
  1462. # If we want it, it's here.
  1463. self.defer = None
  1464. self.keepalive = task.LoopingCall(self.awake)
  1465. self.keepalive.start(30)
  1466. self.menu()
  1467. def __del__(self):
  1468. log.debug("ProxyMenu {0} RIP".format(self))
  1469. def whenDone(self):
  1470. self.defer = defer.Deferred()
  1471. # Call this to chain something after we exit.
  1472. return self.defer
  1473. def menu(self):
  1474. box = Boxes(30, color=self.c)
  1475. self.queue_game.put(box.top())
  1476. self.queue_game.put(
  1477. box.row(self.c + "{0:^30}".format("TradeWars Proxy Active")))
  1478. self.queue_game.put(box.middle())
  1479. def menu_item(ch: str, desc: str):
  1480. row = self.c1 + " {0} {1}- {2}{3:25}".format(ch, self.c2, self.c1, desc)
  1481. self.queue_game.put(box.row(row))
  1482. # self.queue_game.put(
  1483. # " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  1484. # )
  1485. menu_item("D", "Display Report again")
  1486. # menu_item("Q", "Quest")
  1487. # if hasattr(self.game, 'portdata'):
  1488. # ports = len(self.game.portdata)
  1489. # else:
  1490. # ports = '?'
  1491. menu_item("P", "Port CIM Report ({0})".format(len(self.game.gamedata.ports)))
  1492. # if hasattr(self.game, 'warpdata'):
  1493. # warps = len(self.game.warpdata)
  1494. # else:
  1495. # warps = '?'
  1496. menu_item("W", "Warp CIM Report ({0})".format(len(self.game.gamedata.warps)))
  1497. menu_item("T", "Trading Report")
  1498. menu_item("S", "Scripts")
  1499. menu_item("X", "eXit")
  1500. self.queue_game.put(box.bottom())
  1501. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  1502. def awake(self):
  1503. log.info("ProxyMenu.awake()")
  1504. self.game.queue_player.put(" ")
  1505. def port_report(self, portdata: dict):
  1506. # self.portdata = portdata
  1507. # self.game.portdata = portdata
  1508. self.queue_game.put("Loaded {0} ports.".format(len(portdata)) + self.nl)
  1509. self.welcome_back()
  1510. def warp_report(self, warpdata: dict):
  1511. # self.warpdata = warpdata
  1512. # self.game.warpdata = warpdata
  1513. self.queue_game.put("Loaded {0} sectors.".format(len(warpdata)) + self.nl)
  1514. self.welcome_back()
  1515. def make_trade_report(self):
  1516. log.debug("make_trade_report()")
  1517. ok_trades = []
  1518. best_trades = []
  1519. # for sector, pd in self.game.gamedata.ports.items():
  1520. for sector in sorted(self.game.gamedata.ports.keys()):
  1521. pd = self.game.gamedata.ports[sector]
  1522. if not GameData.port_burnt(pd):
  1523. pc = pd['class']
  1524. # Ok, let's look into it.
  1525. if not sector in self.game.gamedata.warps:
  1526. continue
  1527. warps = self.game.gamedata.warps[sector]
  1528. for w in warps:
  1529. # Verify that we have that warp's info, and that the sector is in it.
  1530. # (We can get back from it)
  1531. if w in self.game.gamedata.warps and sector in self.game.gamedata.warps[w]:
  1532. # Ok, we can get there -- and get back!
  1533. if w > sector and w in self.game.gamedata.ports and not GameData.port_burnt(self.game.gamedata.ports[w]):
  1534. # it is > and has a port.
  1535. wd = self.game.gamedata.ports[w]
  1536. wc = wd['class']
  1537. # 1: "BBS",
  1538. # 2: "BSB",
  1539. # 3: "SBB",
  1540. # 4: "SSB",
  1541. # 5: "SBS",
  1542. # 6: "BSS",
  1543. # 7: "SSS",
  1544. # 8: "BBB",
  1545. if pc in (1,5) and wc in (2,4):
  1546. best_trades.append(self.game.gamedata.port_trade_show(sector, w))
  1547. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  1548. elif pc in (2,4) and wc in (1,5):
  1549. best_trades.append(self.game.gamedata.port_trade_show(sector, w))
  1550. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  1551. elif GameData.port_trading(pd['port'], self.game.gamedata.ports[w]['port']):
  1552. # ok_trades.append( "{0:5} -=- {1:5}".format(sector,w))
  1553. ok_trades.append(self.game.gamedata.port_trade_show(sector, w))
  1554. yield
  1555. self.trade_report.append("Best Trades: (org/equ)")
  1556. self.trade_report.extend(best_trades)
  1557. self.trade_report.append("Ok Trades:")
  1558. self.trade_report.extend(ok_trades)
  1559. # self.queue_game.put("BEST TRADES:" + self.nl + self.nl.join(best_trades) + self.nl)
  1560. # self.queue_game.put("OK TRADES:" + self.nl + self.nl.join(ok_trades) + self.nl)
  1561. def show_trade_report(self, *_):
  1562. self.game.trade_report = self.trade_report
  1563. for t in self.trade_report:
  1564. self.queue_game.put(t + self.nl)
  1565. self.welcome_back()
  1566. def player(self, chunk: bytes):
  1567. """ Data from player (in bytes). """
  1568. chunk = chunk.decode("latin-1", "ignore")
  1569. key = chunk.upper()
  1570. log.debug("ProxyMenu.player({0})".format(key))
  1571. # Stop the keepalive if we are activating something else
  1572. # or leaving...
  1573. self.keepalive.stop()
  1574. if key == "T":
  1575. self.queue_game.put(self.c + key + self.r + self.nl)
  1576. # Trade Report
  1577. # do we have enough information to do this?
  1578. # if not hasattr(self.game, 'portdata') and not hasattr(self.game, 'warpdata'):
  1579. # self.queue_game.put("Missing portdata and warpdata." + self.nl)
  1580. # elif not hasattr(self.game, 'portdata'):
  1581. # self.queue_game.put("Missing portdata." + self.nl)
  1582. # elif not hasattr(self.game, 'warpdata'):
  1583. # self.queue_game.put("Missing warpdata." + self.nl)
  1584. # else:
  1585. if True:
  1586. # Yes, so let's start!
  1587. self.trade_report = []
  1588. d = coiterate(self.make_trade_report())
  1589. d.addCallback(self.show_trade_report)
  1590. return
  1591. elif key == "P":
  1592. self.queue_game.put(self.c + key + self.r + self.nl)
  1593. self.game.gamedata.reset_ports()
  1594. # Activate CIM Port Report
  1595. report = CIMPortReport(self.game)
  1596. d = report.whenDone()
  1597. d.addCallback(self.port_report)
  1598. d.addErrback(self.welcome_back)
  1599. return
  1600. elif key == "W":
  1601. self.queue_game.put(self.c + key + self.r + self.nl)
  1602. self.game.gamedata.reset_warps()
  1603. # Activate CIM Warp Report
  1604. report = CIMWarpReport(self.game)
  1605. d = report.whenDone()
  1606. d.addCallback(self.warp_report)
  1607. d.addErrback(self.welcome_back)
  1608. return
  1609. elif key == "S":
  1610. self.queue_game.put(self.c + key + self.r + self.nl)
  1611. # Scripts
  1612. self.activate_scripts_menu()
  1613. return
  1614. elif key == "D":
  1615. self.queue_game.put(self.c + key + self.r + self.nl)
  1616. # (Re) Display Trade Report
  1617. if self.trade_report:
  1618. for t in self.trade_report:
  1619. self.queue_game.put(t + self.nl)
  1620. else:
  1621. self.queue_game.put("Missing trade_report." + self.nl)
  1622. # self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  1623. # self.queue_game.put(pformat(self.warpdata).replace("\n", "\n\r") + self.nl)
  1624. elif key == "Q":
  1625. self.queue_game.put(self.c + key + self.r + self.nl)
  1626. # This is an example of chaining PlayerInput prompt calls.
  1627. ask = PlayerInput(self.game)
  1628. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  1629. # Display the user's input
  1630. d.addCallback(ask.output)
  1631. d.addCallback(
  1632. lambda ignore: ask.prompt(
  1633. "What is your favorite color?", 10, name="color"
  1634. )
  1635. )
  1636. d.addCallback(ask.output)
  1637. d.addCallback(
  1638. lambda ignore: ask.prompt(
  1639. "What is the meaning of the squirrel?",
  1640. 12,
  1641. name="squirrel",
  1642. digits=True,
  1643. )
  1644. )
  1645. d.addCallback(ask.output)
  1646. def show_values(show):
  1647. log.debug(show)
  1648. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  1649. d.addCallback(lambda ignore: show_values(ask.keep))
  1650. d.addCallback(self.welcome_back)
  1651. # On error, just return back
  1652. # This doesn't seem to be getting called.
  1653. # d.addErrback(lambda ignore: self.welcome_back)
  1654. d.addErrback(self.welcome_back)
  1655. return
  1656. elif key == "X":
  1657. self.queue_game.put(self.c + key + self.r + self.nl)
  1658. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  1659. self.observer.load(self.save)
  1660. self.save = None
  1661. # It isn't running (NOW), so don't try to stop it.
  1662. # self.keepalive.stop()
  1663. self.keepalive = None
  1664. # Ok, this is a HORRIBLE idea, because the prompt might be
  1665. # outdated.
  1666. # self.queue_game.put(self.prompt)
  1667. self.prompt = None
  1668. # Possibly: Send '\r' to re-display the prompt
  1669. # instead of displaying the original one.
  1670. self.game.queue_player.put("d")
  1671. # Were we asked to do something when we were done here?
  1672. if self.defer:
  1673. reactor.CallLater(0, self.defer.callback)
  1674. # self.defer.callback()
  1675. self.defer = None
  1676. return
  1677. self.keepalive.start(30, True)
  1678. self.menu()
  1679. def activate_scripts_menu(self):
  1680. self.observer.disconnect("player", self.player)
  1681. self.observer.connect("player", self.scripts_player)
  1682. self.scripts_menu()
  1683. def deactivate_scripts_menu(self, *_):
  1684. self.observer.disconnect("player", self.scripts_player)
  1685. self.observer.connect("player", self.player)
  1686. self.welcome_back()
  1687. def scripts_menu(self, *_):
  1688. c1 = merge(Style.BRIGHT + Fore.CYAN)
  1689. c2 = merge(Style.NORMAL + Fore.CYAN)
  1690. box = Boxes(40, color=c1)
  1691. self.queue_game.put(box.top())
  1692. self.queue_game.put(box.row(c1 + "{0:^40}".format("Scripts")))
  1693. self.queue_game.put(box.middle())
  1694. def menu_item(ch, desc):
  1695. row = " {0}{1} {2}-{3} {4:35}".format(c1, ch, c2, c1, desc)
  1696. # self.queue_game.put(
  1697. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  1698. # )
  1699. self.queue_game.put(box.row(row))
  1700. menu_item("1", "Ports (Trades between two sectors)")
  1701. menu_item("2", "Explore (Strange new sectors)")
  1702. menu_item("3", "Space... the final frontier...")
  1703. menu_item("X", "eXit")
  1704. self.queue_game.put(box.bottom())
  1705. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  1706. def scripts_player(self, chunk: bytes):
  1707. """ Data from player (in bytes). """
  1708. chunk = chunk.decode("latin-1", "ignore")
  1709. key = chunk.upper()
  1710. if key == '1':
  1711. self.queue_game.put(self.c + key + self.r + self.nl)
  1712. # Activate this magical event here
  1713. ports = ScriptPort(self.game)
  1714. d = ports.whenDone()
  1715. # d.addCallback(self.scripts_menu)
  1716. # d.addErrback(self.scripts_menu)
  1717. d.addCallback(self.deactivate_scripts_menu)
  1718. d.addErrback(self.deactivate_scripts_menu)
  1719. return
  1720. elif key == '2':
  1721. self.queue_game.put(self.c + key + self.r + self.nl)
  1722. explore = ScriptExplore(self.game)
  1723. d = explore.whenDone()
  1724. d.addCallback(self.deactivate_scripts_menu)
  1725. d.addErrback(self.deactivate_scripts_menu)
  1726. return
  1727. elif key == '3':
  1728. self.queue_game.put(self.c + key + self.r + self.nl)
  1729. space = ScriptSpace(self.game)
  1730. d = space.whenDone()
  1731. d.addCallback(self.deactivate_scripts_menu)
  1732. d.addErrback(self.deactivate_scripts_menu)
  1733. return
  1734. elif key == 'X':
  1735. self.queue_game.put(self.c + key + self.r + self.nl)
  1736. self.deactivate_scripts_menu()
  1737. return
  1738. else:
  1739. self.queue_game.put(self.c + "?" + self.r + self.nl)
  1740. self.scripts_menu()
  1741. def welcome_back(self, *_):
  1742. log.debug("welcome_back")
  1743. self.keepalive.start(30, True)
  1744. self.menu()