flexible.py 60 KB

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